views:

67

answers:

1

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?

+6  A: 

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.

Peter Hansen
This is exactly what I want! Thanks!