How to catch SyntaxError Exception in Python?


A SyntaxError occurs any time the parser finds source code it does not understand. This can be while importing a module, invoking exec, or calling eval(). Attributes of the exception can be used to find exactly what part of the input text caused the exception.

We rewrite the given code to handle the exception and find its type

Example

try:
print eval('six times seven')
except SyntaxError, err:
print 'Syntax error %s (%s-%s): %s' % \
(err.filename, err.lineno, err.offset, err.text)
print err

Output

C:/Users/TutorialsPoint1/~.py
Syntax error <string> (1-9): six times seven
invalid syntax (<string>, line 1)

Updated on: 12-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements