【问题标题】:Python handling errors after handling an error inside try-except block在 try-except 块中处理错误后 Python 处理错误
【发布时间】: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


【解决方案1】:

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 过滤。

【讨论】:

    【解决方案2】:

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

    try:
        print(1)
        assert 2 + 2 == 5
    except AssertionError:
        try:
            print(3)
            print(2/0)
        except:
            print(4) # this except block will execute during print(2/0)
    except:
        pass #this except block will never execute
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多