8.5. 异常链
raise
语句允许可选的 from
子句,它通过设置所引发异常的 __cause__
属性来启用异常链。 例如:
raise RuntimeError from OSError
这在你要转换异常时很有用。 例如:
>>> def func():
... raise IOError
...
>>> try:
... func()
... except IOError as exc:
... raise RuntimeError('Failed to open database') from exc
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 2, in func
OSError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
RuntimeError
跟在 from
之后的表达式必须是一个异常或为 None
。 当在一个异常处理程序或 finally
子句中又引发了一个异常时异常链将自动生成。 异常链可使用 from None
形式来禁用:
>>> try:
... open('database.sqlite')
... except IOError:
... raise RuntimeError from None
...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
RuntimeError