How to rethrow exception in Python without losing the original traceback


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


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”:

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s