Python在try-except块内处理错误后处理错误

Python在try-except块内处理错误后处理错误,python,error-handling,try-except,Python,Error Handling,Try Except,在这段代码中,通过except-AssertionError:处理断言错误后,except:print(4)不起作用 但是如果我在AssertionError之后创建一个错误,如下所示: try: print(1) assert 2 + 2 == 5 except AssertionError: print(3) except: print(4) try: print(1) assert 2 + 2 == 5 except AssertionE

在这段代码中,通过
except-AssertionError:
处理断言错误后,
except:print(4)
不起作用

但是如果我在AssertionError之后创建一个错误,如下所示:

try:
    print(1)
    assert 2 + 2 == 5
except AssertionError:
    print(3)
except:
    print(4)

try:
    print(1)
    assert 2 + 2 == 5
except AssertionError:
    print(3)
    print(2/0)
except:
    print(4)
它会产生如下错误:

try:
    print(1)
    assert 2 + 2 == 5
except AssertionError:
    print(3)
except:
    print(4)

try:
    print(1)
    assert 2 + 2 == 5
except AssertionError:
    print(3)
    print(2/0)
except:
    print(4)
回溯(最近一次呼叫最后一次):
文件“”,第3行,在
断言2+2==5
断言错误
在处理上述异常期间,发生了另一个异常:
回溯(最近一次呼叫最后一次):
文件“”,第6行,在
打印(2/0)
ZeroDivision错误:被零除

但是为什么呢?它也应该排除那个错误。因为该错误发生在try-except块内。

try-except
块中,过滤的唯一错误是发生在
try
语句下的错误。例如,如果要触发除之外的最后一个
而不是
断言错误
,则可以尝试:

试试看:
印刷品(1)
raise(IOError)#触发最后一个
断言2+2==5
除断言错误外:
印刷品(3)
除:
印刷品(4)
应输出:

1
4.
请记住,任何不在
try
语句下的错误都不能被
过滤,除非

正如正确描述的那样,
zeroditionerror
不会出现在
try
块内。如果需要从第一个
except
块中捕获该异常,则需要执行以下操作:

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
块内。异常块中的代码就是代码。它本身不受错误的保护。