[英]python: recover exception from try block if finally block raises exception
说我有这样的代码:
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中引发的异常,还是它永远消失了?
注意:我没有考虑用例; 这只是好奇心。
我找不到任何关于这是否已被移植并且没有方便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__
之前,有关原始异常的信息不可用。
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
块中抛出异常的代码是个好主意 - 通常你只是用它来进行清理等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.