python - 为什么 "except"语句中的无效异常名称不会立即导致 NameError?

标签 python

考虑这个例子,有一个故意的错字:

try:
    print("Hello!")
    raise ValueError("?")
except ValueErro:
    print("Error!")
finally:
    print("World!")

处理显式引发的 ValueError 会导致 NameError:

Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
ValueError: ?

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
NameError: name 'ValueErro' is not defined

但是,如果 ValueError 未被 引发:

try:
    print("Hello!")
except ValueErro:
    print("Error!")
finally:
    print("World!")

然后没有异常发生Hello!World! 被简单地打印出来。

为什么没有NameError是由错字ValueErro(不存在这样的名称)引起的?这不应该提前检测到吗?

我可以使用不同的语法来确保提前发现问题吗?

最佳答案

在@DYZ 发表评论后,我找到了正确的搜索词来获得答案。

https://docs.python.org/3/tutorial/errors.html#handling-exceptions

The try statement works as follows.

  • First, the try clause (the statement(s) between the try and except keywords) is executed.

  • If no exception occurs, the except clause is skipped and execution of the try statement is finished.

探索这个问题的另一个资源。

https://dbaktiar-on-python.blogspot.com/2009/07/python-lazy-evaluation-on-exception.html

-

我的解决方案向前推进:

# Explicitly bind the Exception Names in a non-lazy fashion.
errors = (KeyboardInterrupt, ValueErro) # Caught!
try:
    print("Hello!")
    raise ValueError("?")
except errors:
    print("Error!")
finally:
    print("World!")

-

tl;dr - 如果 try 子句无一异常(exception)地执行,则完全跳过 except 子句。

关于python - 为什么 "except"语句中的无效异常名称不会立即导致 NameError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48373506/

相关文章:

python - 从 2D numpy 数组快速计算随机 3D numpy 数组

python - 'list' 对象在 Decimal 列表上不可调用

python - 从两侧实现 __rmul__,python

python - 如何从Python3中的输入字符串创建字典

python - 有没有办法在 Raspberry Pi 4 上获得 GPU 加速以进行深度学习?

python - 禁用 Python 中的 Plotly 以任何形式与网络通信

python - 尽管我给了它一个整数,但我却收到了“TypeError:预期为整数参数, float ”

python - 如何获取音频设备和名称

python - 在 Python 中更改 cmd 提示大小

python - 如何将 pygame 表面转换为 PIL 图像?