简体   繁体   English

python:如果finally块引发异常,则从try块恢复异常

[英]python: recover exception from try block if finally block raises exception

Say I have some code like this: 说我有这样的代码:

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

The output is: 输出是:

try block failed: in the finally

From the point of that print statement, is there any way to access the exception raised in the try, or has it disappeared forever? 从print语句的角度来看,有没有办法访问try中引发的异常,还是它永远消失了?

NOTE: I don't have a use case in mind; 注意:我没有考虑用例; this is just curiosity. 这只是好奇心。

I can't find any information about whether this has been backported and don't have a Py2 installation handy, but in Python 3, e has an attribute called e.__context__ , so that: 我找不到任何关于这是否已被移植并且没有方便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__))

gives: 得到:

Exception('in the try',)

According to PEP 3314 , before __context__ was added, information about the original exception was unavailable. 根据PEP 3314 ,在添加__context__之前,有关原始异常的信息不可用。

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,)

However, It would be a good idea to avoid having code that is likely to throw an exception in the finally block - usually you just use it to do cleanup etc. anyway. 但是,避免使用可能在finally块中抛出异常的代码是个好主意 - 通常你只是用它来进行清理等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM