Python异常为什么需要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()

我错过了什么吗?

  • 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

参考文档

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容