21

Consider these two snippets:

try:
    a+a=a
except SyntaxError:
    print "first exception caught"

.

try:
    eval("a+a=a")
except SyntaxError:
    print "second exception caught"

In the second case the "second exception .." statement is printed (exception caught), while in the first one isn't.

Is first exception (lets call it "SyntaxError1") any different from second one ("SyntaxError2")?

Is there any way to catch SyntaxError1 (thus supressing compilation-time errors)? Wrapping large blocks of code in eval is unsatisfactory ;)

gorsky
  • 2,282
  • 1
  • 16
  • 22
  • Suppressing compile-time errors???? What can that possibly mean? Can you provide some definition for the use case in which you want unparseable code to parse? What is supposed to happen? How bad can the code be and yet still be "parsed"? What are you talking about? – S.Lott Dec 07 '09 at 01:05
  • Question was focused mainly on possible inconsistency of SyntaxErrors thrown in different situation. Alex explained that there's no inconsistency at all, and all the described behaviour consists in compiler's mechanisms of constructing higher-level structure of try/except. One probable use case might be uploading by a trusted developer *.py file with some functionality (simple plugin system?), with necessity of validating its syntax right after upload. – gorsky Dec 07 '09 at 09:26

2 Answers2

25

In the first case, the exception is raised by the compiler, which is running before the try/except structure even exists (since it's the compiler itself that will set it up right after parsing). In the second case, the compiler is running twice -- and the exception is getting raised when the compiler runs as part of eval, after the first run of the compiler has already set up the try/except.

So, to intercept syntax errors, one way or another, you have to arrange for the compiler to run twice -- eval is one way, explicit compile built-in function calls another, import is quite handy (after writing the code to another file), exec and execfile other possibilities yet. But however you do it, syntax errors can be caught only after the compiler has run one first time to set up the try/except blocks you need!

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • I wasn't aware of variety of solutions. Especially one with explicit import solves my hidden case elegantly. Thanks a lot, Alex! – gorsky Dec 06 '09 at 20:19
4

Short answer: No.

Syntax errors happen when the code is parsed, which for normal Python code is before the code is executed - the code is not executing inside the try/except block since the code is not executing, period.

However when you eval or exec some code, then you are parsing it at runtime, so you can catch the exception.

Dave Kirby
  • 25,806
  • 5
  • 67
  • 84