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?
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.
精彩评论