[英]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.