gorsky
gorsky

Reputation: 2332

Why can I catch a SyntaxError (or IndentationError or TabError) raised by eval'd code, but not caused by the source code itself?

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

Upvotes: 22

Views: 2231

Answers (2)

Dave Kirby
Dave Kirby

Reputation: 26552

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.

Upvotes: 5

Alex Martelli
Alex Martelli

Reputation: 881785

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!

Upvotes: 26

Related Questions