18

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.)

jrdioko
  • 32,230
  • 28
  • 81
  • 120
  • Don't ask questions just so you can answer them yourself. SO isn't a wiki of random data; it's answers to questions that people are *actually asking*. – Glenn Maynard Apr 19 '10 at 18:22
  • 4
    @Glenn Maynard: Guess _you_ are wrong: http://meta.stackexchange.com/questions/12513/should-i-not-answer-my-own-questions – Curd Apr 19 '10 at 18:25
  • Answering your own question if you figure the answer out after asking it is fine. Asking a question *just so you can answer it* is completely different. – Glenn Maynard Apr 19 '10 at 20:13
  • 3
    It's different, but not necessarily against the spirit of the rules. There are many copies of this question on meta; this one has a number of useful opinions, including some mildly to both sides of this issue: http://meta.stackexchange.com/questions/17463/ – Personman Apr 20 '10 at 00:15
  • Ultimately, people have different opinions and the site doesn't give an adequately explicit answer anywhere. Given the lack of an explicit ban, and the fact that it is easy to do it, I think it's pretty hopeless to try and stop people. I also personally think it's a fine & useful thing to do. – Personman Apr 20 '10 at 00:16
  • The only reason I did this was because of the following line in the FAQ (http://stackoverflow.com/faq): "It's also perfectly fine to ask and answer your own question, but pretend you're on Jeopardy: phrase it in the form of a question." I see now that it's controversial, so I guess I'll avoid it unless something really useful comes along. – jrdioko Apr 20 '10 at 00:46
  • 3
    Well, I'm glad this was put here because it just helped me out. +1. – Shabbyrobe Feb 09 '11 at 14:18

1 Answers1

14

According to the Python documentation, the right way to handle this in Python versions earlier than 2.5 is:

try:
    foo()
except (KeyboardInterrupt, SystemExit):
    raise
except:
    bar()

That's very wordy, but at least it's a solution.

jrdioko
  • 32,230
  • 28
  • 81
  • 120
  • 1
    You should probably make the second `except` also `except Exception:`, to avoid catching other exceptions that aren't supposed to be caught. – Thomas Wouters Apr 19 '10 at 19:05