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!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…