Python Syntax Error is not being caught [duplicate]

[亡魂溺海] 提交于 2019-12-24 16:46:06

问题


from __future__ import print_function

try:
    print "a"
except SyntaxError:
    print('error')

Why is the SyntaxError exception not being caught? I am using Python 2.7

Output:

  File "test", line 4
    print "a"
            ^
SyntaxError: invalid syntax

回答1:


You cannot catch the syntax error in the module itself, because it is thrown before the code is run. Python doesn't run the code as it is compiled line by line, it is the whole file that failed here.

You can do this:

syntaxerror.py

from __future__ import print_function

print "a"

catching.py:

from __future__ import print_function

try:
    import syntaxerror
except SyntaxError:
    print('Error')

because the catching script can be run after compiling, but trying to import syntaxerror then triggers a new compilation task on syntaxerror.py, raising a SyntaxError exception which then can be caught.



来源:https://stackoverflow.com/questions/28385612/python-syntax-error-is-not-being-caught

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!