python - 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")
解决方案
这是因为错误发生在 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
推荐阅读
- pyspark - Pyspark 查看第一行和第二行值并按顺序更新数据
- javascript - Vue路由器如何将输入中的数据替换为url
- php - Laravel 7 多参数路由报错:Facade\Ignition\Exceptions\ViewException Missing required parameters for Route
- javascript - 根据枚举类型值设置属性的类型
- javascript - codeigniter 与文本关联的多个复选框值
- java - 创建对象时,我只得到最后一个索引
- python - 用正则表达式(python)查找完全匹配不起作用
- git - 如何维护一本带有 git 示例的书?
- apache-nifi - apache nifi 使用 GET 发送消息正文
- archlinux - Linux 上的 SSD 修整