的訪問異常消息,我有以下兩個功能:的Python:原始異常
>>> 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
。有沒有辦法訪問異常列表和他們各自的消息,從中我可以簡單地獲取第一個消息?
你運行的是哪個Python版本? –
使用Python 3.4。 – mart1n