How to process syntax errors

Chris Angelico rosuav at gmail.com
Mon Oct 10 12:13:39 EDT 2016


On Tue, Oct 11, 2016 at 2:44 AM, Pierre-Alain Dorange
<pdorange at pas-de-pub-merci.mac.com> wrote:
> Chris Angelico <rosuav at gmail.com> wrote:
>
>> Yes and no. Syntax errors are detected when the script is compiled, so
>> you can't do something like this:
>
> You're right, except that Python is never compiled, it was just checked
> for syntax error before interpreting code.

https://docs.python.org/3/library/functions.html#compile

It's compiled.

>> 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:
>
> Your solution are OK, but that's not very "pythonic".
>
> Python was not design to be used in such a way (intercepting syntax
> error). There was hack to made somthing like requested but that only a
> hack and should not be used in real world.

The error is raised as an exception, which means it is most definitely
meant to be able to be caught. If it were utterly and completely
fatal, it would simply be handled as "print message to standard error,
terminate process" as some forms of fatal error are. (But even in some
of those cases - SystemError and MemoryError - they can still be
raised as exceptions.)

There's nothing unpythonic about catching an exception if you know how
to handle it. My examples did have somewhat unpythonic behaviour
(catching an exception only to print a message and continue), but
that's because they're placeholders.

ChrisA



More information about the Python-list mailing list