mart1n
mart1n

Reputation: 6203

Python: accessing exception message of original exception

I have the following two functions:

>>> def spam():
...     raise ValueError('hello')
...
>>> def catch():
...     try:
...         spam()
...     except ValueError:
...         raise ValueError('test')

Trying to catch the second ValueError exception works just fine and prints the exception's error message:

>>> try:
...     catch()
... except ValueError as e:
...     print(e)
...
test

Is there however any way to access the original exception's error message (i.e. 'hello')? I know I can print the full traceback with:

>>> 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

but I don't exactly want to parse the hello from that string. Is there a way to access the list of exceptions and their respective messages, from which I would simply take the first one?

Upvotes: 4

Views: 3215

Answers (1)

mart1n
mart1n

Reputation: 6203

Figured it out: the original exception is available via e.__cause__.

Upvotes: 4

Related Questions