A KeyboardInterrupt exception occurs when a user manually interrupts the execution of a Python program, usually by pressing Ctrl + C (or Ctrl + Break on some systems). Python raises this exception to stop the currently running program.
while True:
print("Program is running...")
Output
Program is running...
Program is running...
Program is running...
KeyboardInterrupt
Explanation: loop runs indefinitely. When the user presses Ctrl+C, Python interrupts the program and raises a KeyboardInterrupt exception.
This exception is commonly encountered in programs that run continuously, wait for user input, or perform long-running tasks. Handling KeyboardInterrupt allows a program to exit gracefully instead of terminating abruptly.
Common Causes
1. Interrupting an Infinite Loop: A KeyboardInterrupt often occurs when a program is stuck in an endless loop and the user wants to stop it.
while True:
print("Running...")
Output
Running...
Running...
Running...
KeyboardInterrupt
Explanation: loop never ends on its own. Pressing Ctrl+C sends an interrupt signal to Python, causing a KeyboardInterrupt exception.
2. Interrupting User Input: The exception can also occur while a program is waiting for input.
name = input("Enter your name: ")
print(name)
Output
Enter your name:
KeyboardInterrupt
Explanation: program is waiting for user input. Instead of entering a value, pressing Ctrl+C interrupts the operation and raises KeyboardInterrupt.
Handling KeyboardInterrupt
1. try-except Block: most common way to handle KeyboardInterrupt is by using a try-except block.
try:
while True:
user_input = input("Enter something (Ctrl+C to exit): ")
print("You entered:", user_input)
except KeyboardInterrupt:
print("\nProgram terminated by user.")
Output
Enter something (Ctrl+C to exit): Python
You entered: Python
Enter something (Ctrl+C to exit):
Program terminated by user.
Explanation: When the user presses Ctrl+C, the KeyboardInterrupt exception is caught by the except block, allowing the program to exit gracefully.
2. Handling KeyboardInterrupt in Long-Running Processes: For long-running programs, it is often useful to perform cleanup operations before exiting.
import time
try:
print("Processing... Press Ctrl+C to stop.")
for i in range(10):
time.sleep(1)
print(f"Step {i + 1}")
except KeyboardInterrupt:
print("\nProcess interrupted by user.")
finally:
print("Exiting program.")
Output
Processing... Press Ctrl+C to stop.
Step 1
Step 2
Step 3
Process interrupted by user.
Exiting program.
Explanation: If the user interrupts the process, the except block handles the exception. The finally block executes regardless of whether an exception occurs, making it a good place for cleanup tasks.
3. Saving Data Before Exiting: In some applications, you may want to save progress before terminating.
try:
while True:
print("Collecting data...")
except KeyboardInterrupt:
print("\nSaving progress before exit...")
Output
Collecting data...
Collecting data...
Saving progress before exit...
Explanation: When the user interrupts the program, the exception is caught and the program can perform important actions such as saving files, closing connections or storing progress.