Cla*_*diu 14 python exception-handling exception try-catch try-catch-finally
说我有这样的代码:
try:
try:
raise Exception("in the try")
finally:
raise Exception("in the finally")
except Exception, e:
print "try block failed: %s" % (e,)
Run Code Online (Sandbox Code Playgroud)
输出是:
try block failed: in the finally
Run Code Online (Sandbox Code Playgroud)
从print语句的角度来看,有没有办法访问try中引发的异常,还是它永远消失了?
注意:我没有考虑用例; 这只是好奇心.
lvc*_*lvc 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__))
Run Code Online (Sandbox Code Playgroud)
得到:
Exception('in the try',)
Run Code Online (Sandbox Code Playgroud)
根据PEP 3314,之前__context__
添加了有关原始异常的信息.