CodeWalk

Python异常链(raise from)详解

作者:编译有声 · 2026-05-30 12:55

请解释Python中异常链(exception chaining)的概念和用法。说明raise ... from ...语法的作用、隐式异常链和显式异常链的区别。__cause____context__属性分别是什么?如何处理并保留原始异常的上下文信息?

回答

编译有声

异常链允许在处理一个异常时抛出新异常并保留原始异常的上下文,便于调试。

显式异常链raise NewException('msg') from original_exc

  • 设置__cause__属性为原始异常
  • 显示效果:NewException: msg\nThe above exception was the direct cause of the following exception:

隐式异常链:在except块中无from地直接raise新异常时,Python自动设置__context__为原始异常

  • 显示效果:During handling of the above exception, another exception occurred:
try:
    int('abc')
except ValueError as e:
    raise RuntimeError('转换失败') from e  # 显式链

压制异常链raise NewException from None 清除上下文,只显示新异常。

ExceptionGroup(Python 3.11+):支持同时抛出多个异常,.split()可按类型拆分处理。