I want to catch every program error so that I can display those errors in my GUI program, but I find I'm not able to catch certain kinds of error 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"
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 be catched by user
^
SyntaxError: invalid syntax
So, I know I did not catch the exception myself.
How can I catch it?
SyntaxError is thrown before the code is actually run. In particular your error handlers haven't been created executed yet.
(You will notice that if you have anything that generate output in your code, such as print statements, the output will not be generated when there's a problem with the syntax, no matter where they are in the code).
However in the use case you described, I don't really see why you would need to catch SyntaxError. It seems to me that you would want to catch errors that depend on the program's state. SyntaxError don't pop up unexpected. If you were able to run your programs once, you will not a SyntaxError in later invocations (unless, of course, you change the code).