1
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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
quesaionasis
  • 137
  • 1
  • 2
  • 11

1 Answers1

7

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343