开发者

Retrieving doubly raised exceptions original stack trace in python

开发者 https://www.devze.com 2022-12-14 14:26 出处:网络
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?

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号