all Python 3Exceptionsexception
SyntaxError
built-in exceptions
Syntactically invalid code, detected at compile time: eval('1 +').
Syntax
raise SyntaxError
You cannot wrap your own broken source in try/except: the whole file is parsed before anything runs, so the error fires before the first statement executes. Catching it makes sense only for code compiled at runtime — eval(), exec(), compile(), or importing third-party code. The exception carries msg, filename, lineno, offset and text for pinpointing the spot, and IndentationError and TabError are its subclasses.
Examples
try:
eval('1 +')
except SyntaxError as e:
print(type(e).__name__) # → SyntaxError
See also
Open in the full glossarydocs.python.orgReport an inaccuracy