让我们假设您有一些简单的代码,* 您无法控制 *(例如:它位于您正在使用的模块中):
def example():
try:
raise TypeError("type")
except TypeError:
raise Exception("device busy")
为了处理它,我将如何着手访问这个回溯中的TypeError
?
Traceback (most recent call last):
File "/usr/local/google/home/dthor/dev/pyle/pyle/fab/visa_instrument/exception_helpers.py", line 3, in example
raise TypeError("type")
TypeError: type
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/google/home/dthor/dev/pyle/pyle/fab/visa_instrument/exception_helpers.py", line 7, in <module>
example()
File "/usr/local/google/home/dthor/dev/pyle/pyle/fab/visa_instrument/exception_helpers.py", line 5, in example
raise Exception("device busy")
Exception: device busy
我可以做下面的操作,但我不满意,因为我正在做字符串比较--这意味着如果底层模块改变了它们所引发的字符串,事情就会中断(我不控制example()
):
try:
example()
except Exception as err:
if "device busy" in str(err):
# do the thing
pass
# But raise any other exceptions
raise err
我更希望:
try:
example()
except Exception as err:
if TypeError in err.other_errors: # magic that doesn't exist
# do the thing
pass
raise err
甚至
try:
example()
except TypeError in exception_stack: # Magic that doesn't exist
# do the thing
pass
except Exception:
我正在研究traceback
模块和sys.exc_info()
,但还没有任何具体的东西。
跟进:如果异常是 chained,情况会有所不同吗?raise Exception from the_TypeError_exception
1条答案
按热度按时间yizd12fk1#
检查异常的
__context__
:如果使用链式异常,则原始异常也可以通过
__cause__
属性访问。