我有两个文件:fl_fn1.py中的内容:import fl_fn2def fn1(): print("hi") try: fl_fn2.fn2() except: print("inside except") finally: print("finally")fn1()fl_fn2.py中的内容:import sysdef fn2(): print("fn2") sys.exit(0)现在,当我从 Windows 命令提示符调用 fl_fn1.py 时,例如;C:\Program Files\Anaconda3\python.exe C:\Users\User1\Desktop\fl_fn1.py那么我的输出是:hifn2inside exceptfinally但是,当我将 fl_fn1.py 中的异常部分更改为:except Exception as ex: print("inside except")然后我的输出是:hifn2finally异常部分不执行!!!有人可以解释发生了什么。我是 Python 新手。提前致谢 :)
2 回答

胡子哥哥
TA贡献1825条经验 获得超6个赞
SystemExit
继承自BaseException
not from Exception
so 来捕捉你需要except BaseException as e:
的。这是为了防止意外捕获异常except Exception as e:

眼眸繁星
TA贡献1873条经验 获得超9个赞
有一些日志记录可以帮助您了解您的异常类型:
import sys
def fn1():
print("hi")
try:
fn2()
except:
print("Exception type: ",sys.exc_info()[0], " occured.")
print("Exception inherits from: ", sys.exc_info()[0].__bases__)
print("inside except")
finally:
print("finally")
fn1()
正如@Chris_Rands 在他的回复中提到的那样,您会收到SystemExit继承的异常BaseException。
添加回答
举报
0/150
提交
取消