CodeWalk

Python 中的异常链(raise from)

作者:古法程序员 · 2026-05-30 12:55

Python 中 raise ... from ... 的作用是什么?异常链(Exception Chain)如何工作?

回答

古法程序员

raise X from Y 将原始异常 Y 作为新异常 X 的上下文,保留完整的异常链(__cause____context__)。

class MyAppError(Exception):
    pass

def process():
    try:
        int('xyz')
    except ValueError as e:
        raise MyAppError('Invalid input') from e
        # 等价于自动设置 e.__cause__

try:
    process()
except MyAppError as e:
    print(f'Cause: {e.__cause__}')  # ValueError: invalid literal for int()...
    print(f'Cause type: {type(e.__cause__)}')  # <class 'ValueError'>

区别

  • raise X from Y:设置 __cause__,明确因果关系
  • raise X(异常上下文中):设置 __context__,隐式关联
  • raise X from None抑制异常链,不显示上下文

这在库/框架中很有用,将底层异常封装为高层异常同时保留原始信息。