上面的异常在抛出的异常信息中指向什么?

问题描述 投票:0回答:1

最简单的内置异常如下:

>>> 1/0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero

抛出异常信息,然后整个按下就完成了。

定义函数

f1
而不是定义
myException
:

def f1():
    try:
        print(1/0)
    except:
        raise myException('my exception')

致电

f1()

>>> f1()
Traceback (most recent call last):
  File "<stdin>", line 3, in f1
ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in f1
NameError: name 'myException' is not defined

当信息

Traceback (most recent call last):
  File "<stdin>", line 3, in f1
ZeroDivisionError: division by zero

被抛出,

print(1/0)
的异常按照我们一开始看到的那样进行处理。
为什么中间一行的语句是
During handling of the above exception, another exception occurred:
,而不是
After handling of the above exception, another exception occurred:

above exception
语句中的
During handling of the above exception
是什么?它指向
try ... except
中的
f1
结构,而不是
1/0
导致的异常?
如果
above exception
指向
1/0
导致的异常,那么
After handling of the above exception, another exception occurred
更适合在这里描述所有异常!

python exception try-except
1个回答
0
投票

这是异常链,如

raise
声明中所述。你抓住了
ZeroDivisionError
。当您引发
MyException
时,Python 会自动将当前异常添加到其
__cause__
属性中。

这就是您看到列出的两个例外的原因。您提出的那个,以及放入

__cause__
属性的那个。 Python 允许您以多种方式自定义异常,特别是“from”异常。一般来说,就是

raise myException from OtherException

更具体地说,要完全抑制原始异常并将其排除在

__cause__
属性之外,请从
None
:

引发
raise myException from None
© www.soinside.com 2019 - 2024. All rights reserved.