Exception chaining
阅读量:
在 raise
后接 from
可以启用异常链。
# exc must be exception instance or None.
raise RuntimeError from exc
可以用来转义一个异常的信息,例如
try:
raise ConnectionError
except ConnectionError as exc:
raise RuntimeError('Failed to open database') from exc
>>>
Traceback (most recent call last):
File "/home/yuchuan/code/selfuse/test.py", line 20, in <module>
raise ConnectionError
ConnectionError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/yuchuan/code/selfuse/test.py", line 22, in <module>
raise RuntimeError('Failed to open database') from exc
RuntimeError: Failed to open database
表明 RuntimeError
是由 ConnectionError
直接导致的,并且提供了更具体的信息。
若不使用 raise ... from ...
try:
raise ConnectionError
except ConnectionError as exc:
raise RuntimeError('Failed to open database')
>>>
Traceback (most recent call last):
File "/home/yuchuan/code/selfuse/test.py", line 20, in <module>
raise ConnectionError
ConnectionError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/yuchuan/code/selfuse/test.py", line 22, in <module>
raise RuntimeError('Failed to open database')
RuntimeError: Failed to open database
则两个异常会被视为无联系的异常。
可用于对异常进行进一步解释,或者表明引发异常的异常链。使用 from
与否在程序运行结果上并无区别,但在报错输出的解释与程序设计的逻辑上有着明显的区别。应尽量使用 from
使得异常链完整,便于追踪问题所在。
#待整理笔记
反向链接
到头儿啦~