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开发者_StackOverflow社区 blocks of code in eval
is unsatisfactory ;)
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!
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.
精彩评论