You can only catch SyntaxError
if it's thrown out of an eval
, exec
, or import
operation.
>>> try:
... eval('x === x')
... except SyntaxError:
... print "You cannot do that"
...
You cannot do that
This is because, normally, the interpreter parses the entire file before executing any of it, so it detects the syntax error before the try
statement is executed. If you use eval
or its friends to cause more code to be parsed during the execution of the program, though, then you can catch it.
I'm pretty sure this is in the official manual somewhere, but I can't find it right now.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…