Python继承体系下:为何Exception无法捕获sys.exit()抛出的异常?
为何
sys.exit()抛出的异常无法被Exception捕获 首先明确Python的异常层级逻辑:
BaseException是所有异常的顶层父类Exception确实继承自BaseException,但它只是BaseException的子类之一,并非所有BaseException的子类都归属于Exception分支
核心原因:sys.exit()抛出的是SystemExit异常
sys.exit()函数的本质是抛出一个SystemExit异常,而SystemExit是BaseException的直接子类,和Exception是平级关系,并不属于Exception的子类范畴。
所以第一个代码中:
import sys class calc: def learn_exception(self): try: sys.exit() except Exception as exp: print(f'system exited {exp}') print('code running after main execution') c=calc() c.learn_exception()
except Exception块无法匹配到SystemExit异常,程序会直接因未被捕获的SystemExit终止,自然不会执行后续的打印语句。
而第二个代码添加了except BaseException块:
import sys class calc: def learn_exception(self): try: sys.exit() except Exception as exp: print(f'system exited {exp}') except BaseException as ex: print(f'error while running the code {ex}') print('code running after main execution') c=calc() c.learn_exception()
因为SystemExit是BaseException的子类,这个捕获块能匹配到异常,执行打印逻辑后,异常被处理,程序会继续执行后续的打印语句。
额外说明:Python的设计意图
SystemExit、KeyboardInterrupt(Ctrl+C触发)、GeneratorExit这类异常属于流程控制类异常,而非普通的程序错误。Python将它们独立于Exception分支,是为了避免被通用的except Exception意外捕获,防止程序的正常流程控制(比如退出、中断)被错误拦截。
内容的提问来源于stack exchange,提问作者Lijin Durairaj
相关产品推荐
相关产品推荐

