I learned that the SyntaxError is the only error that can not be caught.
for example:
if __name__ == "__main__":
print "main running"
try:
for i in range(3):
except SyntaxError,e:
print "error caught"
finally:
print "i am here"
well, I expect print “main running” could be displayed, well it doesn’t
so does python check all the syntax before it runs?
It is impossible to detect
SyntaxErrorat runtime because invalid syntax compromises the validity of the whole module, not only of the specific line where the author perceives to have made a mistake. Since the interpreter doesn’t understand the author’s intentions, the only thing it can do after failing to read the source is raise the error.As Martin Pieters answered, the failure occurs at the compilation step at which Python reads the whole module and compiles it to memory before running it. However, even without a separate compilation step, the underlying problem with catching inline syntax errors at run-time would remain.
To catch syntax errors at run-time within the same module, one must isolate the erroneous code from the surrounding code. This can be done using the
execstatement or theevalfunction:To catch syntax errors in imported modules, simply put the
try/exceptaround theimportstatement.