python - 为什么我们需要 Python 中的 "finally"子句?

标签 python exception-handling try-finally

我不确定为什么我们在 try...except...finally 语句中需要 finally。在我看来,这个代码块

try:
    run_code1()
except TypeError:
    run_code2()
other_code()

使用 finally 与这个相同:

try:
    run_code1()
except TypeError:
    run_code2()
finally:
    other_code()

我错过了什么吗?

最佳答案

如果你早点回来会有所不同:

try:
    run_code1()
except TypeError:
    run_code2()
    return None   # The finally block is run before the method returns
finally:
    other_code()

比较一下:

try:
    run_code1()
except TypeError:
    run_code2()
    return None   

other_code()  # This doesn't get run if there's an exception.

其他可能导致差异的情况:

  • 如果在 except block 内抛出异常。
  • 如果在 run_code1() 中抛出异常但不是 TypeError
  • 其他控制流语句,例如 continuebreak 语句。

关于python - 为什么我们需要 Python 中的 "finally"子句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11551996/

相关文章:

python - Pandas : Copy recent date's data for missing days

python - 为什么一个简单的 CSV 清理 python 脚本可以工作,而另一个却不能?

python - 有没有办法将 python 代码合并到 moinmoin 页面中?

c# - 在 try-finally block 中等待

c# - 在 C# 中,try-finally 如何捕获原始异常

Python 命名空间位于内置函数和全局函数之间?

c# - 捕获异常、验证输入或两者兼而有之?

c++ - C++ 中的全局异常处理

c# - 如何在异常过滤器 Asp.Net Core 中获取模型对象?

delphi - 我什么时候应该使用 "try" block ,我应该使用哪种?