How to catch SyntaxError Exception in Python?

PythonServer Side ProgrammingProgramming

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)
raja
Published on 06-Dec-2017 13:09:59
Advertisements