4

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?

2
  • What Python version are you running? Commented Jul 18, 2017 at 15:18
  • Using Python 3.4. Commented Jul 18, 2017 at 15:40

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

5 Comments

Unless the exception was raised via the raise ... from ... statement, the original exception is stored in __context__, not __cause__.
@vaultah Ha, interesting. So using print(e.__cause__ or e.__context__) should be the way to go.
any way to do it without accessing a private attribute?
@simpleuser Python hasn't private attributes. You are probably mistaking them for name-mangled attributes (with form __attr: two leading underscores and none trailing), but neither are. If they were they'd have to be called as e._Exception__cause__, which is the most private access that Python has.
@simpleuser What about str(e) to get yout error message? str(ValueError("Some error message")) returns "Some error message".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.