How to process syntax errors

Chris Angelico rosuav at gmail.com
Mon Oct 10 11:24:37 EDT 2016


On Tue, Oct 11, 2016 at 1:13 AM,  <mr.puneet.goyal at gmail.com> wrote:
> Is there any way to capture syntax errors and process them ? I want to write a function which calls every time whenever there is syntax error in the program.
>
> For example,
>
> inside example.py
>
> I just mention below line
>
>
> Obj = myClass()
> Obj xyz
>
> Obj is instance of a class. But there is syntax error on xyz. So I want to grab that error and process.

Yes and no. Syntax errors are detected when the script is compiled, so
you can't do something like this:

try:
    Obj xyz
except SyntaxError:
    print("Try Obj.xyz instead!")

However, you can catch this at some form of outer level. If you're
using exec/eval to run the code, you can guard that:

code = """
obj = MyClass() # using PEP 8 names
obj xyz
"""
try:
    exec(code)
except SyntaxError:
    print("Blah blah blah")

Alternatively, you can put the code into a file and import it:

# otherfile.py
obj = MyClass()
obj xyz

# mainfile.py
try:
    import otherfile
except SyntaxError:
    do_stuff()

This is probably the easiest solution, if your code's already in a
separate file.

ChrisA



More information about the Python-list mailing list