【发布时间】:2019-08-22 13:10:10
【问题描述】:
Python 3 允许从其他异常中引发异常,例如:
try:
raise CustomException()
except CustomException as e:
try:
raise TypeError() from e
except TypeError as e:
print(type(e.__cause__))
CustomException 实例存储在异常对象的__cause__ 属性中。
上面的代码应该打印CustomException。
有没有办法捕捉原始异常而不是新引发的异常?
try:
raise CustomException()
except CustomException as e:
try:
raise TypeError() from e
except CustomException as e:
print(type(e)) # should reach here
覆盖 __subclasscheck__ 不起作用,因为我无权访问该实例,并且无法指定 CustomException is a subclass of all classes or of the cause class。
有没有办法让 Python 认为我们捕获的异常是 __cause__ 类型的?
【问题讨论】:
-
如果你想抓
CustomException,你为什么还要提TypeError? -
自定义异常用于捕获所有异常并返回一个Failure容器。 github.com/dry-python/returns/blob/master/returns/…
标签: python python-3.x exception