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.
This exception is particularly useful during development and testing, as it allows you to terminate long-running or hanging programs gracefully.
KeyboardInterrupt
Occurs When
The user presses Ctrl+C during a program’s execution.
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 purposes to halt execution without modifying the code
KeyboardInterrupt
Example
An example of when the exception appears:
>>> 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.
Related Resources
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.
For additional information on related topics, take a look at the following resources:
By Leodanis Pozo Ramos • Updated May 23, 2025