【问题标题】:python: recover exception from try block if finally block raises exceptionpython:如果finally块引发异常,则从try块中恢复异常
【发布时间】:2012-05-02 04:01:39
【问题描述】:

假设我有一些这样的代码:

try:
    try:
        raise Exception("in the try")
    finally:
        raise Exception("in the finally")
except Exception, e:
    print "try block failed: %s" % (e,)

输出是:

try block failed: in the finally

从该打印语句的角度来看,有什么方法可以访问 try 中引发的异常,还是它永远消失了?

注意:我没有考虑用例;这只是好奇。

【问题讨论】:

    标签: python exception exception-handling try-catch try-catch-finally


    【解决方案1】:

    我找不到任何关于这是否已被反向移植并且没有方便的 Py2 安装的任何信息,但在 Python 3 中,e 有一个名为 e.__context__ 的属性,因此:

    try:
        try:
            raise Exception("in the try")
        finally:
            raise Exception("in the finally")
    except Exception as e:
        print(repr(e.__context__))
    

    给予:

    Exception('in the try',)
    

    根据PEP 3314,在添加__context__之前,原始异常的信息是不可用的。

    【讨论】:

    • 不错,但仅限 py3。无论如何:+1。
    • 啊,很好。所以根据那个 PEP,答案是,“你不能,在 Py2 中,但你可以在 Py3 中”。谢谢!
    【解决方案2】:
    try:
        try:
            raise Exception("in the try")
        except Exception, e:
            print "try block failed"
        finally:
            raise Exception("in the finally")
    except Exception, e:
        print "finally block failed: %s" % (e,)
    

    但是,最好避免在 finally 块中包含可能引发异常的代码 - 通常你只是用它来进行清理等。

    【讨论】:

    • 这只是在进入 finally 块之前吞噬了 "in the try" 异常。
    猜你喜欢
    • 1970-01-01
    • 2014-01-08
    • 1970-01-01
    • 2016-02-12
    • 1970-01-01
    • 2023-03-31
    • 2013-02-23
    • 2012-09-20
    • 1970-01-01
    相关资源
    最近更新 更多