我不确定为什么我们在 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
。 - 其他控制流语句,例如
continue
和break
语句。
关于python - 为什么我们需要 Python 中的 "finally"子句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11551996/