Ad Space — Top Banner

KeyboardInterrupt

Python Python

Severity: Minor

What it means

KeyboardInterrupt is raised when you press Ctrl+C while a Python program is running.
It is not an error — it is Python's way of letting you stop a running program.
You can catch it with try/except to perform cleanup before exiting.

Affected Models

  • Python 3.x
  • Python 2.x
  • Windows
  • macOS
  • Linux

Common Causes

  • User pressed Ctrl+C to stop the program
  • An automated system sent SIGINT to the Python process
  • An IDE's stop button sent an interrupt signal
  • A script running in a terminal was interrupted by the user

How to Fix It

  1. If you intended to stop the program: this is normal behaviour.

    Ctrl+C is the standard way to stop a running Python program.
    KeyboardInterrupt is expected — your program stopped as requested.

  2. To handle it gracefully: wrap your code in try/except KeyboardInterrupt.

    try:
    main()
    except KeyboardInterrupt:
    print('Shutting down...')
    cleanup()
    This lets you save data or close connections before exiting.

  3. For long-running scripts: use signal handlers for cleaner shutdown.

    import signal
    def handler(sig, frame): sys.exit(0)
    signal.signal(signal.SIGINT, handler)
    This gives more control over the shutdown process.

Frequently Asked Questions

Is KeyboardInterrupt an error?

No.
It is an exception, but not an error.
It is Python's mechanism for responding to the user requesting program termination.
It inherits from BaseException, not Exception.

Why does except Exception not catch KeyboardInterrupt?

KeyboardInterrupt inherits from BaseException, not Exception.
This is intentional — except Exception should not prevent users from stopping programs.
Use except KeyboardInterrupt specifically if you need to catch it.