无法捕获语法错误python [英] Failed to catch syntax error python
问题描述
try:
x === x
除了SyntaxError:
print你不能这样做
输出
x === x
^
SyntaxError:无效语法
>
try:
x === x
除了:
打印你不能这样做
像ErrorError,ValueError这样的其他错误是可以捕获的。
想法?
系统规格:
import sys
print(sys.version)
- >
2.7.5(默认,2014年3月9日,22:15:05)
[GCC 4.2.1兼容的Apple LLVM 5.0(clang-500.0.68)]
只能从 eval c
/ code>或 exec
操作。
>> ;>尝试:
... eval('x === x')
...除了SyntaxError:
...打印你不能这样做
...
你不能这样做
这是因为通常,解释器解析完整的文件之前,所以在执行 我很确定这是在官方手册的某个地方,但我现在找不到。 try
语句之前检测出语法错误。如果您在执行程序期间使用 eval
或其朋友导致更多代码被解析,那么您可以抓住它。 / p>
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
or exec
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屋!