无法捕获语法错误python [英] Failed to catch syntax error python

查看:104
本文介绍了无法捕获语法错误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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆