我不知道为什么我们最终需要尝试……最后陈述。在我看来,这个代码块
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()
other_code()
和这个finally的用法一样:
try:
run_code1()
except TypeError:
run_code2()
finally:
other_code()
我遗漏了什么吗?
当前回答
在第一个例子中,如果run_code1()引发了一个不是TypeError的异常,会发生什么?... Other_code()将不会被执行。
与finally: version: other_code()相比,无论引发任何异常,都保证执行。
其他回答
在第一个例子中,如果run_code1()引发了一个不是TypeError的异常,会发生什么?... Other_code()将不会被执行。
与finally: version: other_code()相比,无论引发任何异常,都保证执行。
它们不相等。最后,不管发生什么,代码都会运行*。 它对于清理必须运行的代码非常有用。
*: 正如Mark Byers所评论的,任何导致进程立即终止的事情也会阻止最终代码的运行。 后者可以是os._exit()。或断电,但无限循环或其他东西也属于这一类。
Finally也可以用于在运行主要工作的代码之前运行“可选”代码,而可选代码可能由于各种原因而失败。
在下面的例子中,我们不知道store_some_debug_info会抛出什么样的异常。
我们可以运行:
try:
store_some_debug_info()
except Exception:
pass
do_something_really_important()
但是,大多数lint会抱怨捕捉到的异常过于模糊。此外,由于我们选择只传递错误,except块并没有真正增加值。
try:
store_some_debug_info()
finally:
do_something_really_important()
上面的代码与第一个代码块具有相同的效果,但更简洁。
如果你早点回来,情况就不一样了:
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块内抛出异常。 如果在run_code1()中抛出异常,但它不是TypeError。 其他控制流语句,如continue和break语句。
最后是“清理行动”的定义。finally子句在离开try语句之前的任何事件中执行,无论是否发生异常(即使您没有处理它)。
我赞同拜尔斯的例子。