考虑这个例子,有一个故意的错字:
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/