python - 处理try-except block 内的错误后,Python处理错误

标签 python error-handling try-except

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/

相关文章:

validation - Scala中的错误处理单子(monad)?尝试与验证

python - 语法错误 : 'continue' not properly in loop

python - 人口蒙特卡洛实现

asynchronous - 无法看到在julia @spawn方法内发生的错误

python - 从其他数据帧顺序更新 pandas 列

asp.net-mvc - 如何捕获ASP.NET MVC中未处理的错误?

python - 如何在Windows 10中手动停止Python程序?

python - 如何有条件地跳过pd.read_html()中不包含表的html文件?

python - 如何使用 python 和 Django 高效导出大型 Excel 文件

python - 在 python 中多次访问 mmap 对象