Python 中的异常链(raise from)
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:抑制异常链,不显示上下文
这在库/框架中很有用,将底层异常封装为高层异常同时保留原始信息。