【发布时间】:2020-01-29 04:40:57
【问题描述】:
try:
print(1)
assert 2 + 2 == 5
except AssertionError:
print(3)
except:
print(4)
在此代码中,except AssertionError: 处理该断言错误后,except: print(4) 不起作用。
但是如果我像这样在 AssertionError 之后创建一个错误:
try:
print(1)
assert 2 + 2 == 5
except AssertionError:
print(3)
print(2/0)
except:
print(4)
它给出了这样的错误:
Traceback (most recent call last):
File "<pyshell#14>", line 3, in <module>
assert 2 + 2 == 5
AssertionError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<pyshell#14>", line 6, in <module>
print(2/0)
ZeroDivisionError: division by zero
但是为什么呢?它也应该排除该错误。因为该错误发生在 try except 块内。
【问题讨论】:
-
try块内不会发生错误。异常块内的代码就是代码。它本身没有受到错误保护。
标签: python error-handling try-except