Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to catch SyntaxError Exception in Python?

When I run the following line of code, I get error

print eval('six times seven')

How do I handle this exception and find its type?


1 Answer
codefoxx

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

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)
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.