Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
859 views
in Technique[技术] by (71.8m points)

exception - SyntaxError inconsistency in Python?

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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...