finally中return压制异常
- finally中最好不要设置return工作,尽可能得只做清理工作
def parse_int(s):
try:
return int(s)
finally:
return 0
print(parse_int("good"))
运行结果:
0
这个时候也不会抛出异常,因为通过finally中得return压制住了
raise直接抛异常
当只是写raise时,表示抛出最后一次被激活的异常
如果上次没有被激活的异常时,表示错误异常
import sys
try:
raise
except BaseException as e:
print(e)
print(sys.exc_info())
finally:
print("ok")
运行结果:
exceptions must derive from BaseException
(<class 'TypeError'>, TypeError('exceptions must derive from BaseException',), <traceback object at 0x000001714977A388>)
ok