Skip to content
Tutorials Center
My learning

Topics

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.

Python
import sys
sys.exit(2)   # raises SystemExit(2); the process exits with status 2

Try it

Python sys.exit() is an exception

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.

Python Handling Ctrl+C and generator close

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

Python
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 and sys.exit() is ignored. Write except Exception: for "all ordinary errors".
  • SystemExit in threads. Raising it in a non-main thread only ends that thread, not the whole program.
  • Cleanup. finally blocks and with statements run during an exit or interrupt, so files are closed and locks released. After handling KeyboardInterrupt, usually re-raise or call sys.exit(130), the conventional status for "interrupted".
  • os._exit() is different. It ends the process immediately with no exception, no finally and no cleanup; it is meant for child processes after fork().
  • 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() and quit() exist for the interactive prompt (added by the site module); in scripts use sys.exit().
  • GeneratorExit should not be swallowed: after catching it, the generator must not yield again, or Python raises RuntimeError.
  • Async code. asyncio uses CancelledError (also a BaseException subclass since 3.8) to stop tasks, and asyncio.run() turns Ctrl+C into cancelling the main task.
  • Libraries should not call sys.exit(); raise a normal exception and let the application decide.