error-handling - Python : If error occurs anywhere, do specific line of code

标签 error-handling try-except

我正在尝试编写一个脚本来处理大量数据。当然,存在潜在的错误。在脚本中,我需要连接到数据库。如果脚本遇到错误,则代码永远不会到达终止与数据库的连接的位置。我想在我的python代码中包含一些可以识别错误发生的东西,无论在哪里,如果没有其他原因,至少可以关闭那些数据库。是否存在这样的东西?我知道我可以使用try/except,但这只有在我确切知道可以从哪里得到错误的情况下才能起作用?我基本上是在寻找一个万能的包来关闭我的数据库,以防在我未曾预料到的位置发生错误。

最佳答案

即使出现错误也要运行某些清理代码,请使用finally块:

try:
   # do stuff, possible exception
except:
   # run this if exception
finally:
   # always run this, even if exception
引用:https://docs.python.org/3/tutorial/errors.html#defining-clean-up-actions

关于error-handling - Python : If error occurs anywhere, do specific line of code,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64125281/

相关文章:

python - 为什么这个 Python 键盘中断不起作用? (在 PyCharm 中)

python - 尝试除了递归或 while 循环?

python - try 和 except 都引发异常。

javascript - 我的Alexa技能给了我一个困难的错误,我不知道该错误的出处

python - (OSError) 异常处理 (ConnectionRefusedError) 错误

error-handling - 使用单子(monad)批量进行失败的转换?

codeigniter - 我在codeigniter中使用resize()库时出错

python - 如何在for循环python中跳过AttributeError并继续循环

error-handling - 如何在随后的业务流程步骤中显示从自定义REST API端点返回的错误?

iphone - 由于一般错误 (1095),目前无法处理应用程序 info.plist 验证