CodeWalk

BaseException vs Exception vs Warning 的区别

作者:孤独的心 · 2026-05-30 12:55

请解释Python异常层次结构中BaseExceptionExceptionWarning的区别。为什么建议捕获Exception而非BaseException?什么时候需要捕获BaseExceptionWarning类别和warnings模块如何控制警告输出?

回答

孤独的心

异常层次BaseExceptionException → 常规异常;BaseExceptionKeyboardInterruptSystemExit

为什么不捕获BaseException

try:
    while True: pass
except BaseException:  # 糟糕!捕获了Ctrl+C
    pass  # 程序无法被终止
  • KeyboardInterrupt(Ctrl+C)继承BaseException
  • SystemExitsys.exit())继承BaseException
  • GeneratorExit(生成器关闭)继承BaseException

应捕获`Exception(几乎所有编程异常都继承自此)。

Warning:不是异常,不会中断程序。warnings.warn('msg', DeprecationWarning)

  • 默认:DeprecationWarningPendingDeprecationWarning对最终用户隐藏
  • 控制:warnings.filterwarnings('error')将警告转为异常;simplefilter设置默认行为
  • 分类:DeprecationWarningUserWarningSyntaxWarningRuntimeWarning

何时捕获BaseException:极少数场景如守护进程清理(try-finally优先)、框架调试钩子。