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
但为什么?它也应该排除该错误。因为该错误发生在tryexcept块内。
最佳答案
在try - except
块中,过滤的唯一错误是在try
语句下发生的错误。例如,如果要触发最后一个except
而不是AssertionError
,则可以尝试:
try:
print(1)
raise(IOError) #To trigger the last except
assert 2 + 2 == 5
except AssertionError:
print(3)
except:
print(4)
应该输出:
1
4
请记住,
try
不能直接过滤不在except
语句下的任何错误。
关于python - 处理try-except block 内的错误后,Python处理错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59960566/