BaseException vs Exception vs Warning 的区别
请解释Python异常层次结构中BaseException、Exception和Warning的区别。为什么建议捕获Exception而非BaseException?什么时候需要捕获BaseException?Warning类别和warnings模块如何控制警告输出?
回答
孤独的心
异常层次:BaseException → Exception → 常规异常;BaseException → KeyboardInterrupt、SystemExit等
为什么不捕获BaseException:
try:
while True: pass
except BaseException: # 糟糕!捕获了Ctrl+C
pass # 程序无法被终止
KeyboardInterrupt(Ctrl+C)继承BaseExceptionSystemExit(sys.exit())继承BaseExceptionGeneratorExit(生成器关闭)继承BaseException
应捕获`Exception(几乎所有编程异常都继承自此)。
Warning:不是异常,不会中断程序。warnings.warn('msg', DeprecationWarning)
- 默认:
DeprecationWarning、PendingDeprecationWarning对最终用户隐藏 - 控制:
warnings.filterwarnings('error')将警告转为异常;simplefilter设置默认行为 - 分类:
DeprecationWarning、UserWarning、SyntaxWarning、RuntimeWarning等
何时捕获BaseException:极少数场景如守护进程清理(try-finally优先)、框架调试钩子。