Can Syntax Errors be handled?

SyntaxError is a perfectly ordinary built-in exception. It is not special in any way. Only the circumstances of when it’s (usually) thrown are a bit unusual.

A syntax error means that the code featuring said error cannot be parsed. It doesn’t even begin to be a valid program, hence it cannot be executed. Therefore SyntaxError exceptions are raised before the program is run, and hence can’t be caught from within the program.

More specifically, this exception is raised by the parser. Because the parser runs fully before the code is executed, rather then interleaved with it, a program can’t catch its own syntax errors.

The parser itself is just another program though: Code invoking the parser can catch SyntaxErrors like every other exception (because it is like every other exception). Examples of “invoking the parser” include:

  • compile, exec, eval
  • import statements
  • Several functions in modules like ast, tokenizer, parser, etc.

Leave a Comment

Can Syntax Errors be handled?

SyntaxError is a perfectly ordinary built-in exception. It is not special in any way. Only the circumstances of when it’s (usually) thrown are a bit unusual.

A syntax error means that the code featuring said error cannot be parsed. It doesn’t even begin to be a valid program, hence it cannot be executed. Therefore SyntaxError exceptions are raised before the program is run, and hence can’t be caught from within the program.

More specifically, this exception is raised by the parser. Because the parser runs fully before the code is executed, rather then interleaved with it, a program can’t catch its own syntax errors.

The parser itself is just another program though: Code invoking the parser can catch SyntaxErrors like every other exception (because it is like every other exception). Examples of “invoking the parser” include:

  • compile, exec, eval
  • import statements
  • Several functions in modules like ast, tokenizer, parser, etc.

Leave a Comment