a_list = ['First error', 'Second error']
try:
print(a_list[3])
except Exception as e:
try:
# the following line is a developer mistake - they wanted to print progress as 1/10 but wrote 1/0
print(1 / 0)
except ZeroDivisionError as f:
print('Inner exception (f):', f)
print('Outer exception (e):', e)
print('Outer exception referenced:', f.__context__)#为什么这里输出的是e的信息
print('Is it the same object:', f.__context__ is e)
"""
output:
Inner exception (f): division by zero
Outer exception (e): list index out of range
Outer exception referenced: list index out of range
Is it the same object: True
"""
下面是官网的解释
When raising a new exception while another exception is already being handled, the new exception's context attribute is automatically set to the handled exception. An exception may be handled when an except or finally clause, or a with statement, is used.
大概意思就是
当另一个异常已经被处理时引发一个新异常,新异常的 __context__属性会自动设置为已处理的异常
。except当使用or finally子句或语句时,可能会处理异常with。
如果在处理一个异常时引发了一个新异常,则新异常在其__context__新异常的属性中将具有旧异常。但是,如果新异常包括from子句(raise NewException from OldException),则新异常还将在其__cause__属性中具有旧异常。
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!