KeyboardInterrupt not raised or caught in the case of broad Exception
python, python-2.7, signals
Solution
You cannot catch `KeyboardInterrupt` by catching `Exception` because the former inherits from `BaseException` only. You can read about this in the docs:
exception `KeyboardInterrupt`
Raised when the user hits the interrupt key (normally Control-C or Delete). During execution, a check for interrupts is made regularly. Interrupts typed when a built-in function `input()` or `raw_input()` is waiting for input also raise this exception. The exception inherits from `BaseException` so as to not be accidentally caught by code that catches `Exception` and thus prevent the interpreter from exiting. (Emphasis mine)
This means that you would have to do:
except BaseException, e:
But that is considered a bad practice. It would be better to just catch `KeyboardInterrupt` itself like in your first example.
Problem
Could somebody explain to me the following. Lets take a look at the code: ``` if __name__ == '__main__': try: while 1: x = 2+2 except KeyboardInterrupt: print('yo') ``` If I run this, wait for a while, then press Ctrl+C, an exception will be processed and the message `yo` will be printed. If we change the code to catch a broad exception like this: ``` if __name__ == '__main__': try: while 1: x = 2+2 except Exception, e: print('yo') print(e) ``` Run it, wait for a while, press Ctrl+C, the KeyboardInterrupt exception will not be caught. According to Python documentation: Python installs a small number of signal handlers by default: SIGPIPE is ignored (so write errors on pipes and sockets can be reported as ordinary Python exceptions) and SIGINT is translated into a KeyboardInterrupt exception. All of these can be overridden. So, why in the second case is this exception not caught or even raised?