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

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

问题描述

我知道如果我想重新引发异常,我只需在相应的 except 块中使用不带参数的 raise.但是给定一个嵌套的表达式,如

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

如何在不破坏堆栈跟踪的情况下重新引发 SomeError?在这种情况下,单独的 raise 会重新引发最近的 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?

推荐答案

从 Python 3 开始,回溯存储在异常中,因此一个简单的 raise e 将做(大部分)正确的事情:

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

try:
    something()
except SomeError as e:
    try:
        plan_B()
    except AlsoFailsError:
        raise e  # or raise e from None - see below

产生的回溯将包括一个额外的通知,即 SomeError 在处理 AlsoFailsError 时发生(因为 raise eexcept AlsoFailsError).这是一种误导,因为实际发生的事情是相反的 - 我们遇到了 AlsoFailsError,并在尝试从 SomeError 中恢复时对其进行了处理.要获得不包含 AlsoFailsError 的回溯,请将 raise e 替换为 raise e from None.

The traceback produced will include an additional notice that SomeError occurred while handling AlsoFailsError (because of raise e being inside except AlsoFailsError). This is misleading because what actually happened is the other way around - we encountered AlsoFailsError, and handled it, while trying to recover from SomeError. To obtain a traceback that doesn't include AlsoFailsError, replace raise e with raise e from None.

在 Python 2 中,您将异常类型、值和回溯存储在局部变量中,并使用 raise 的三参数形式:

In Python 2 you'd 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

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

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