定义一个简单的异常类:class myException(Exception): pass
定义一个函数
def f1():
try:
print(1/0)
except:
raise myException('my exception')
运行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
__main__.myException: my exception
写一段代码调用f1():
try:
f1()
except myException as e:
print(e)
为何输出结果仅仅有 my exception
下面这些信息为何不出现?
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
__main__.myException: my exception
那些信息是 python 针对没有被处理的 exception 打印出来的。
你后一个写法把 exception 处理掉了,就不会打印了。
第一个写法中,是在处理 exception 的过程中又抛出了另一个 exception 。新的 exception 就没有被处理了。