首页 > 解决方案 > python捕获“所有其他错误”类型的示例案例

问题描述

在下面的代码中,当我运行它时,它假设用“except Exception as error:”来捕获所有错误,返回“不可能”,但当我设置神秘值 = a 时,情况并非如此,它给了我一个 NameError。没看懂,谁能帮忙解释一下?谢谢。

mystery_value = a

try:
    print(10/mystery_value)
except ZeroDivisionError as error:
    print("Can't divide by zero")
except Exception as error:
    print("Not possible")

标签: pythonerror-handling

解决方案


这是因为错误发生在 try except 块之前。它出现在第一行,因为a没有引用任何东西,并且它没有运行到 try except。如果您将 a 替换为“a”,则异常会起作用。

mystery_value = 'a' # replace a with 'a'

try:
    print(10/mystery_value)
except ZeroDivisionError as error:
    print("Can't divide by zero")
except Exception as error:
    print("Not possible")

输出

Not possible

推荐阅读