Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 562
mart1n Avatar asked Oct 27 '25 10:10

mart1n


1 Answers

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

like image 59
mart1n Avatar answered Oct 29 '25 00:10

mart1n



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!