Python Reference ยท Exceptions
Python KeyboardInterrupt and SystemExit
Reference for Python KeyboardInterrupt, SystemExit and GeneratorExit: why they derive from BaseException, sys.exit() codes, Ctrl+C handling and cleanup.
KeyboardInterrupt is raised when the user presses Ctrl+C (the interrupt signal) while Python is running. SystemExit is raised by sys.exit() and tells the interpreter to finish. A third relative, GeneratorExit, is raised inside a generator when it is closed early.
These three do not derive from Exception. They inherit directly from BaseException, so an ordinary except Exception: lets them pass. That is deliberate: a program should still be stoppable even when its error handling is broad.
import sys sys.exit(2) # raises SystemExit(2); the process exits with status 2
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
import sys sys.exit() # status 0 sys.exit(3) # status 3 sys.exit("message") # prints message to stderr, status 1 try: long_running() except KeyboardInterrupt: cleanup() raise SystemExit(130)
| Name | Description |
|---|---|
SystemExit.code |
The value passed to sys.exit(): None or 0 means success, another integer is the status, anything else is printed to stderr and the status is 1. |
Raises when: sys.exit() is called (SystemExit); Ctrl+C is received (KeyboardInterrupt); a generator's close() is called or it is garbage collected while suspended (GeneratorExit).
Usage notes
- Never use a bare
except:. It also catches these exceptions, so Ctrl+C stops working andsys.exit()is ignored. Writeexcept Exception:for "all ordinary errors". SystemExitin threads. Raising it in a non-main thread only ends that thread, not the whole program.- Cleanup.
finallyblocks andwithstatements run during an exit or interrupt, so files are closed and locks released. After handlingKeyboardInterrupt, usually re-raise or callsys.exit(130), the conventional status for "interrupted". os._exit()is different. It ends the process immediately with no exception, nofinallyand no cleanup; it is meant for child processes afterfork().- Exit codes matter to shells and schedulers: 0 is success and non-zero is failure. A script ending with an uncaught exception exits with status 1.
exit()andquit()exist for the interactive prompt (added by thesitemodule); in scripts usesys.exit().GeneratorExitshould not be swallowed: after catching it, the generator must notyieldagain, or Python raisesRuntimeError.- Async code.
asynciousesCancelledError(also aBaseExceptionsubclass since 3.8) to stop tasks, andasyncio.run()turns Ctrl+C into cancelling the main task. - Libraries should not call
sys.exit(); raise a normal exception and let the application decide.