我不知道为什么我们在try...except...finally语句中需要finally。在我看来,这个代码块
try:
run_code1()
except TypeError:
run_code2()
other_code()
与使用finally的相同:
try:
run_code1()
except TypeError:
run_code2()
finally:
other_code()
我错过了什么吗?
finally is for defining "clean up actions". The finally clause is executed in any event before leaving the try statement, whether an exception (even if you do not handle it) has occurred or not.
如果出现异常,而异常里面退出程序,第一种写法other_code()不会被执行到,而第二种会执行完再退出。
You can use finally to make sure files or resources are closed or released regardless of whether an exception occurs, even if you don't catch the exception. (Or if you don't catch that specific exception.)
myfile = open("test.txt", "w")
try:
myfile.write("the Answer is: ")
myfile.write(42) # raises TypeError, which will be propagated to caller
finally:
myfile.close() # will be executed before TypeError is propagated