Python SyntaxError Exception
Example
A SyntaxError occurs if a parenthesis is missing:
print("Hello World"
Try it Yourself »
Definition and Usage
The SyntaxError exception occurs when the code does not follow the rules of the Python language, for example when a parenthesis or a colon is missing.
Python checks the syntax before the program runs, so a SyntaxError stops the whole program, also the lines before the error.
You cannot catch a SyntaxError in the same file. You can only catch it when you run code from a string, with eval() or exec(), see the example below.
IndentationError is a kind of SyntaxError.
Exception Handling
Example
Handling the SyntaxError in a try...except statement:
try:
eval("5 +")
except SyntaxError:
print("The code has a syntax error")
Try it Yourself »
Related Pages
Read more about handling errors in our Python Try Except Tutorial.