How to Get the Traceback of an Exception Outside of the Exception Block in Python
If you're catching exceptions and storing them for use after exiting the exception block (assuming you didn't raise
), it's not obvious how to print the full traceback message as it would be seen if that error had been raised at that point in the code.
In fact, you have full access to the traceback message at the point the error occurred from the Exception
object.
The most common occurrence of this for me is when I want to catch and save exceptions encountered in threads, but wait until the all threads have completed to do something with the exceptions.
Here's how you can print the traceback message from an exception (as it would be displayed at that point in the code) after exiting the exception block:
import traceback
# example where we catch and store exception we need later
exception_container = []
try:
1/0
except Exception as exc:
exception_container.append(exc)
# two options to print the proper traceback message from the point where the exception occurred
# second option requires python 3.5+
for ex in exception_container:
print("".join(traceback.format_exception(etype=type(ex), value=ex, tb=ex.__traceback__)))
print("".join(traceback.TracebackException.from_exception(ex).format()))
Thanks to this post for pointing out the second option.