31
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)]

humanbeing
  • 1,617
  • 3
  • 17
  • 30

2 Answers2

58

You can only catch SyntaxError if it's thrown out of an eval, exec, or import 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.

zwol
  • 135,547
  • 38
  • 252
  • 361
  • Hi @zwol, thanks for your answer. But Python is an interpreted language, so shouldn't the file be parsed instruction by instruction? – white-hawk-73 Jul 06 '20 at 07:36
  • 2
    @ak0817 No, Python doesn't work that way. It has an ahead-of-time compilation stage that parses the entire file and constructs a "bytecode" representation (that's what's in ".pyc" files); the actual interpreter loop runs on the bytecode. Most "interpreted" languages nowadays do something like this, because it's much more efficient. In fact I can't think of _any_ language that is _specified_ to parse the file line by line at runtime. – zwol Jul 06 '20 at 14:23
23

SyntaxErrors get raised when the file/code is parsed, not when that line of code is executed. The reason for this is simple -- If the syntax is wrong at a single point in the code, the parser can't continue so all code after that line is un-parseable.

In other words, you can only catch syntax errors when python is trying to parse something. This includes exec, eval, import:

>>> try:
...    import junk
... except SyntaxError:
...    print "Woo"
... 
Woo

and various things regarding ast and the like.

Note that the python tutorial even distinguishes between SyntaxError and other exceptions although the distinction isn't as clear as the tutorial makes it seem (since you can in fact catch SyntaxError if you know when they get raised).

mgilson
  • 300,191
  • 65
  • 633
  • 696