python finally的作用_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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值