使用(c
python)
Python 3.6.4和
Python 2.7.14测试了以下代码块.
显式提升ValueError语句已注释掉,以下代码运行并打印“Hello!”然后是“世界!”即使没有ValueErro符号存在.
取消注释引发的ValueError语句并引发ValueError,并引发未定义的预期NameError:name“ValueErro”.
try:
print("Hello!")
# raise ValueError("?")
except ValueErro:
print("Error!")
finally:
print("World!")
我希望NameError在运行时处理except块之前很好地显示出来.
是否有一种不同的语法可以在解析步骤中更积极地检查名称/符号?
这是一个实现错误吗?
谢谢阅读!
最佳答案 在@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子句无异常执行,则完全跳过except子句.