最简单的内置异常如下:
>>> 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
更适合在这里描述所有异常!