未能捕获语法错误 python [英] Failed to catch syntax error python
问题描述
尝试:x===x除了语法错误:打印你不能那样做"
输出
x===x^语法错误:无效语法
这也没有抓住它
尝试:x===x除了:打印你不能那样做"
其他错误,如 NameError、ValueError,都是可以捕获的.
想法?
系统规格:
导入系统打印(系统版本)
->2.7.5(默认,2014 年 3 月 9 日,22:15:05)[GCC 4.2.1 兼容 Apple LLVM 5.0 (clang-500.0.68)]
如果 SyntaxError
是从 eval
, exec
,或import
操作.
这是因为,通常情况下,解释器会在执行任何文件之前解析整个文件,因此它会在执行 try
语句之前检测语法错误.但是,如果您使用 eval
或其朋友在程序执行期间解析更多代码,那么您可以捕获它.
我很确定这在某处的官方手册中,但我现在找不到.
try:
x===x
except SyntaxError:
print "You cannot do that"
outputs
x===x
^
SyntaxError: invalid syntax
this does not catch it either
try:
x===x
except:
print "You cannot do that"
Other errors like NameError, ValueError, are catchable.
Thoughts?
System specs:
import sys
print(sys.version)
-> 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)]
You can only catch SyntaxError
if it's thrown out of an eval
, exec
, or import
operation.
>>> try:
... eval('x === x')
... except SyntaxError:
... print "You cannot do that"
...
You cannot do that
This is because, normally, the interpreter parses the entire file before executing any of it, so it detects the syntax error before the try
statement is executed. If you use eval
or its friends to cause more code to be parsed during the execution of the program, though, then you can catch it.
I'm pretty sure this is in the official manual somewhere, but I can't find it right now.
这篇关于未能捕获语法错误 python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!