如何在嵌套try / except块中重新引发异常? [英] How to re-raise an exception in nested try/except blocks?

查看:526
本文介绍了如何在嵌套try / except块中重新引发异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如果我想重新引发一个例外,我简单地使用中加入 c>块。但是给出一个嵌套的表达式,如

  try:
something()
除了SomeError作为e:
尝试:
plan_B()
除了AlsoFailsError:
raise e#我想提出SomeError,就好像plan_B()
#没有提高AlsoFailsError

如何重新提高 SomeError 打破堆栈跟踪?在这种情况下, raise 会重新提起更近的 AlsoFailsError 。或者如何重构我的代码以避免这个问题?

解决方案

您可以在本地存储异常类型,值和追溯变量,并使用三参数形式的提高

  try:
something()
除了SomeError:
t,v,tb = sys.exc_info()
try:
plan_B()
except AlsoFailsError:
raise t,v,tb

在Python 3中,追溯存储在异常中,所以 raise e 将做(主要)正确的事情:

  try:
something()
except SomeError as e:
try:
plan_B()
except AlsoFailsError:
raise e

上面唯一的问题是它会产生一个稍微误导的追溯,告诉你处理 AlsoFailsError (因为 raise e 发生 SomeError 中除了AlsoFailsError ),其中事实上几乎完全相反,我们处理 AlsoFailsError ,同时尝试从 SomeError 。要禁用此行为并获得一个从未提及 AlsoFailsError 的追溯,请用 raise raise e from None


I know that if I want to re-raise an exception, I simple use raise without arguments in the respective except block. But given a nested expression like

try:
    something()
except SomeError as e:
    try:
        plan_B()
    except AlsoFailsError:
        raise e  # I'd like to raise the SomeError as if plan_B()
                 # didn't raise the AlsoFailsError

how can I re-raise the SomeError without breaking the stack trace? raise alone would in this case re-raise the more recent AlsoFailsError. Or how could I refactor my code to avoid this issue?

解决方案

You can store the exception type, value, and traceback in local variables and use the three-argument form of raise:

try:
    something()
except SomeError:
    t, v, tb = sys.exc_info()
    try:
        plan_B()
    except AlsoFailsError:
        raise t, v, tb

In Python 3 the traceback is stored in the exception, so raise e will do the (mostly) right thing:

try:
    something()
except SomeError as e:
    try:
        plan_B()
    except AlsoFailsError:
        raise e

The only problem with the above is that it will produce a slightly misleading traceback that tells you that SomeError occurred while handling AlsoFailsError (because of raise e inside Except AlsoFailsError), where in fact the almost exact opposite occurred - we handled AlsoFailsError while trying to recover from SomeError. To disable this behavior and get a traceback that never mentions AlsoFailsError, replace raise e with raise e from None.

这篇关于如何在嵌套try / except块中重新引发异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆