Avoiding accidentally catching KeyboardInterrupt and SystemExit in Python 2.4

Posted by jrdioko on Stack Overflow See other posts from Stack Overflow or by jrdioko
Published on 2010-04-19T18:09:08Z Indexed on 2010/04/19 18:13 UTC
Read the original article Hit count: 388

Filed under:
|

In Python scripts, there are many cases where a keyboard interrupt (Ctrl-C) fails to kill the process because of a bare except clause somewhere in the code:

try:
    foo()
except:
    bar()

The standard solution in Python 2.5 or higher is to catch Exception rather than using bare except clauses:

try:
    foo()
except Exception:
    bar()

This works because, as of Python 2.5, KeyboardInterrupt and SystemExit inherit from BaseException, not Exception. However, some installations are still running Python 2.4. How can this problem be handled in versions prior to Python 2.5?

(I'm going to answer this question myself, but putting it here so people searching for it can find a solution.)

© Stack Overflow or respective owner

Related posts about python

Related posts about python-2.4