1

What is the point of the SyntaxError builtin in python? It doesn't seem to have any practical use because SyntaxErrors are found by the python interpreter before the code is run. Example:

try:
    &@!5_+ #SyntaxError
except: pass

This fails with a SyntaxError because the SyntaxError is found before it can be handled. Now this works and fails silently, like intended:

try:
    raise SyntaxError
except: pass

However, I have never seen a function or class or anything raise a SyntaxError. So why does this exist so easy to use and catch when the only use seems to be raising it pointlessly? Is there someplace that python raises a SyntaxError that it can be caught? Or does it just exits in the builtin scope just to be there?

Eb946207
  • 748
  • 8
  • 26

3 Answers3

3

I believe that documentation is self-explanatory:

Raised when the parser encounters a syntax error. This may occur in an import statement, in a call to the built-in functions exec() or eval(), or when reading the initial script or standard input (also interactively).

vishes_shell
  • 22,409
  • 6
  • 71
  • 81
1

The easy way to attack this question is to search for how this exception gets raised in practice. I have the CPython source code already downloaded, so I did

find . -type f -name "*.py" | xargs grep "raise SyntaxError"

We see that there is a utility script that does file conversions that raises a syntax error if it doesn't see the magic byte in the correct place. Additionally, the xml library uses them in parsing XPath expressions.

This suggests that it is meant to be used by user code that deals with parsing other things as well. A Google search for "raise SyntaxError" shows many results of this being used in this way.

I'm not terribly familiar with the Python internals, but I assume being able to handle an error in paring source code the same way they handle other errors makes things nicer. Plus eval etc. have to raise something, as the docs and the previous answer state.

Eb946207
  • 748
  • 8
  • 26
1

There's very rarely a use for using SyntaxError in your program. It's usually only used for the python interpreter when it encounters invalid syntax.

The only case I can think of that you would ever catch a SyntaxError is if you are using exec or eval on an unknown value. For example, if you were executing user input, then the input may be invalid and you would need to catch the SyntaxError.

Pika Supports Ukraine
  • 3,612
  • 10
  • 26
  • 42