我有以下两个功能:
>>> def spam():
... raise ValueError('hello')
...
>>> def catch():
... try:
... spam()
... except ValueError:
... raise ValueError('test')
尝试捕获第二个ValueError
异常可以正常工作并打印异常的错误消息:
>>> try:
... catch()
... except ValueError as e:
... print(e)
...
test
是否有办法访问原始异常的错误消息(即'hello'
)?我知道我可以打印完整的追溯:
>>> try:
... catch()
... except ValueError as e:
... import traceback
... print(traceback.format_exc())
...
Traceback (most recent call last):
File "<stdin>", line 3, in catch
File "<stdin>", line 2, in spam
ValueError: hello
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 5, in catch
ValueError: test
但我并不想完全解析该字符串中的hello
。有没有办法访问异常列表及其各自的消息,我只能从中获取第一个消息?
答案 0 :(得分:3)
想出来:原始例外可通过e.__cause__
获得。