Skip to content

KeyboardInterrupt

In Python, KeyboardInterrupt is a built-in exception that occurs when the user interrupts the execution of a program using the keyboard. This happens when the user presses a key combination, which is usually Ctrl+C on most operating systems. It inherits directly from BaseException instead of Exception, so code that catches Exception won’t accidentally swallow it and stop the interpreter from exiting.

This exception is particularly useful during development and testing, as it lets you stop long-running or hanging programs without having to kill the process by other means. Python can raise it after almost any bytecode instruction, though, so an interrupted program may be left in an inconsistent state.

KeyboardInterrupt Occurs When

  • The user presses Ctrl+C during a program’s execution
  • The user presses the interrupt key on systems where it isn’t Ctrl+C, such as Del
  • The process receives a SIGINT signal while Python’s default signal handler is installed

KeyboardInterrupt Can Be Used When

  • Stopping a running program during an infinite loop or long computation
  • Interrupting a script that waits for user input or a network response
  • Testing and debugging to halt execution without modifying the code

KeyboardInterrupt Example

An example of when the exception appears:

Language: Python
>>> while True:
...     print("This will run forever unless interrupted")
...
This will run forever unless interrupted
This will run forever unless interrupted
This will run forever unless interrupted
This will run forever unless interrupted
Traceback (most recent call last):
    ...
KeyboardInterrupt

In production code, you shouldn’t catch this exception, as doing so could prevent users from stopping the program execution when necessary. Raising KeyboardInterrupt manually is uncommon since it’s specifically for user interrupts.

Python's Built-In Exceptions: A Walkthrough With Examples

Tutorial

Python's Built-in Exceptions: A Walkthrough With Examples

In this tutorial, you'll get to know some of the most commonly used built-in exceptions in Python. You'll learn when these exceptions can appear in your code and how to handle them. Finally, you'll learn how to raise some of these exceptions in your code.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Aug. 16, 2026