首页 > 解决方案 > 如果与 catch 子句相对应的 finally 子句包含 return 语句,如何捕获在 catch 子句中引发的异常?

问题描述

假设:


如果这令人困惑,那么一些代码如下所示:

def e():
    out = "hello world"
    try:
        raise ValueError("my name is Sarah")
    except BaseException as exc:

        # HOW DO I CATCH THE FIRST OF THE FOLLOWING
        # exceptions from outside of this, current,
        # except clause?

        raise ValueError("secret info it would be good to know")
        raise AttributeError
        raise type("Hell", (Exception,), dict())()
        [0, 1, 2][99999]

        class AnythingYouCanThinkOf(Exception):
            pass

        raise AnythingYouCanThinkOf

        out = "definitely not `hello world`"
    finally:
        return out

print(e())
print("No error!!! wowza!")

上面的代码打印:

hello world
No error!!! wowza!

如果我们注释掉该行,out = "hello world"那么我们得到UnboundLocalError: local variable 'out' referenced before assignment. 但是,我仍然不确定如何恢复ValueError("secret info it would be good to know")

此外,如果您将几乎相同的代码放在函数之外e,您会得到非常不同的结果。为什么?

if True:
    out = "hello world"
    try:
        raise ValueError("my name is Bob")
    except BaseException as exc:

        # HOW DO I CATCH THE FIRST OF THE FOLLOWING
        # exceptions from outside of this, current,
        # except clause?

        raise ValueError("what is this madness?")

        class AnythingYouCanThinkOf(Exception):
            pass

        raise AnythingYouCanThinkOf

        out = "definitely not `hello world`"
    finally:
        print(out)

以上导致ValueError: what is this madness?之前未处理的异常,我们得到No error!!! wowza!

标签: pythonpython-3.xexceptiontry-catch

解决方案


推荐阅读