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.