Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving doubly raised exceptions original stack trace in python

If I have a scenario where an exception is raised, caught, then raised again inside the except: block, is there a way to capture the initial stack frame from which it was raised?

The stack-trace that gets printed as python exits describes the place where the exception is raised a second time. Is there a way to raise the exception such that the stack frame that the exception was originally thrown is shown?

like image 576
user196835 Avatar asked Dec 23 '22 07:12

user196835


1 Answers

It's a common mistake to re-raise an exception by specifying the exception instance again, like this:

except Exception, ex:
     # do something
     raise ex

This strips the original traceback info and starts a new one. What you should do instead is this, without explicitly specifying the exception (i.e. use a "bare" raise):

except Exception, ex:
    # do something
    raise

This preserves all the original information in the stack trace. See this section in the docs for somewhat helpful background.

like image 193
Peter Hansen Avatar answered Apr 28 '23 04:04

Peter Hansen