How to rethrow exception in Python without losing the original traceback

Scenario:

catch an exception in one place, and raise it again in another.

Solution:

when the original exception was caught:

exc_info = sys.exc_info()

In a difference place, we get the reference to the exc_info stored above:

In Python  2:

raise exc_info[0], exc_info[1], exc_info[2]

In Python 3:

       raise exc_info[0].with_traceback(exc_info[1], exc_info[2])

When should we use “raise e?” here ‘e’ is an exception that you’ve just caught, Never. Doing so will always lose the traceback information from the previous frames on the stack, and obfuscate the point of origin of the original error.

See the difference between “raise e” and “raise”:

http://www.markbetz.net/2014/04/30/re-raising-exceptions-in-python/ http://nedbatchelder.com/blog/200711/rethrowing_exceptions_in_python.html http://stackoverflow.com/questions/14503751/how-to-write-exception-reraising-code-thats-compatible-with-both-python-2-and-p


Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s