13

说我有一些像这样的代码:蟒蛇:从try块恢复异常,如果finally块产生异常

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 

从这个print语句的一点,就是有什么办法可以访问try中引发的异常,或者它永远消失了吗?

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

回答

14

我无法找到任何有关这是否已经被移植并没有安装的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__之前,有关原始异常的信息是不可用的。

+0

不错,但只有py3。反正:+1。 – ch3ka 2012-04-20 14:57:13

+1

啊,很好。所以根据该PEP,答案是,“你不能,在Py2中,但你可以在Py3中”。谢谢! – Claudiu 2012-04-20 15:26:35

0
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块一个好主意 - 通常你只是用它做清理等无妨。

+2

它只是吞下try中的''异常,然后才到达finally块。 – 2013-08-22 07:45:37