Why SyntaxError can't be captured by user code?

I want to catch every programming error so that I can display those errors in my graphics program, but found that I cannot catch some kinds of errors like SyntaxError and IndentError.

For example:

import traceback

zero = 0

try:
    print "start..."
v = 3/zero # deliberately no indention, SyntaxError cannot be caught

except:
    print "Oooooooooooooops"
    traceback.print_exc()
    exit(1)

print "run ok"

      

Console output:

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

      

So I know I haven't caught the exception myself.

How can I catch him?

+3


source to share


1 answer


SyntaxError is thrown before running the code. In particular, your error handlers have not been created yet.

(You will notice that if you have something that generates output in your code, such as print instructions, no output will be generated if there is a syntax problem, no matter where they are in the code.)



However, in the use case you described, I really don't understand why you need to catch the SyntaxError. It seems to me that you want to catch errors depending on the state of the program. SyntaxError does not appear unexpectedly. If you could run your programs once, you will not use SyntaxError in subsequent calls (unless, of course, you change the code).

+2


source







All Articles