如何在 Python 中捕获 SystemExit 异常?
pythonserver side programmingprogramming
在 Python 文档中,SystemExit 不是 Exception 类的子类。BaseException 类是 SystemExit 的基类。因此,在给定的代码中,我们用 BaseException 替换 Exception 以使代码正常工作
示例
try: raise SystemExit except BaseException: print "It works!"
输出
It works!
异常继承自 BaseException 而不是 StandardError 或 Exception,因此不会被捕获 Exception 的代码意外捕获。
我们宁愿这样编写代码
示例
try: raise SystemExit except SystemExit: print "It works!"
输出
It works!