15

Consider the following code and traceback:

>>> try: ... raise KeyboardInterrupt ... except KeyboardInterrupt: ... raise Exception ... Traceback (most recent call last): File "<stdin>", line 2, in <module> KeyboardInterrupt During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<stdin>", line 4, in <module> Exception >>> 

I'd like to print only the most recent traceback (the one in which Exception was raised).
How can this be achieved?


From the above example, I'd like to print the following, as if raise Exception had been called outside the except clause.

Traceback (most recent call last): File "<stdin>", line 4, in <module> Exception 
2
  • By "get", do you mean get the exception object, or do you mean not printing the context information? If you mean the second, do you want some sort of global interpreter setting, or something that applies to specific exceptions? Commented Dec 19, 2013 at 9:37
  • Raising exceptions when an exception is already present in Python 3 Commented Dec 19, 2013 at 9:39

1 Answer 1

36

The perfect question for me.

You can suppress the exception context, that is the first part of the traceback, by explicitly raising the exception from None:

>>> try: raise KeyboardInterrupt except: raise Exception from None Traceback (most recent call last): File "<pyshell#4>", line 4, in <module> raise Exception from None Exception 

This was formalized in PEP 409 and further improved in PEP 415. The original bug request for this was filed by myself btw.


Note that suppressing the context will not actually remove the context from the new exception. So you can still access the original exception:

try: try: raise Exception('inner') except: raise Exception('outer') from None except Exception as e: print(e.__context__) # inner 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.