python - Why can't SyntaxError be caught by user code? -


this question has answer here:

i want catch every program error can display errors in gui program, find i'm not able catch kinds of error syntaxerror , indenterror.

for example:

import traceback  0 = 0  try:     print "start..." v = 3/zero # deliberately no indention, syntaxerror cannot caught  except:     print "oooooooooooooops"     traceback.print_exc()     exit(1)  print "run ok" 

the console output is:

  file "d:\w\personal\chj\python-try\catch-syntaxerror\catch_syntax_err.py", line 8     v = 3/zero # ``syntaxerror: invalid syntax``, cannot catched user     ^ syntaxerror: invalid syntax 

so, know did not catch exception myself.

how can catch it?

syntaxerror thrown before code run. in particular error handlers haven't been created executed yet.

(you notice if have generate output in code, such print statements, output not generated when there's problem syntax, no matter in code).

however in use case described, don't see why need catch syntaxerror. seems me want catch errors depend on program's state. syntaxerror don't pop unexpected. if able run programs once, not syntaxerror in later invocations (unless, of course, change code).


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -