在Python 3中,有一个有用的raise ... from ...
功能可以重新引发异常。也就是说,如何从引发的异常中找到原始(/重新引发的)异常?这是一个(愚蠢的)示例,上面有注释,以证明我的意思-
def some_func():
try:
None() # TypeError: 'NoneType' object is not callable
except as err:
raise Exception("blah") from err
try:
some_func()
except as err:
# how can I access the original exception (TypeError)?
它位于__cause__
引发的异常的属性中。摘自的文档raise
声明,它说有关raise ... from ...
:
该
from
子句用于异常链接:如果给出,则第二个表达式必须是另一个异常类或实例,然后将其附加到引发的异常作为__cause__
属性(可写)。如果未处理引发的异常,则将同时打印两个异常。
因此,在您给定的场景中,repr
设置__cause__
属性:
def some_func():
try:
None() # TypeError: 'NoneType' object is not callable
except TypeError as err:
raise Exception("blah") from err
try:
some_func()
except Exception as er:
print(repr(er.__cause__))
将打印出:
TypeError("'NoneType' object is not callable",)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句