KeyboardInterrupt: What It Means and How to Fix It
Error reference
KeyboardInterrupt
Language
Severity
LowWhen it happens
KeyboardInterrupt is raised when the user presses Ctrl+C (or the interrupt key) to stop a running program.
Potential fixes
Catch KeyboardInterrupt explicitly if you need to perform cleanup before exiting. Use a finally block to ensure resources like file handles and network connections are closed regardless of how the program exits. Avoid catching BaseException broadly.
Related errors
Deep dive
KeyboardInterrupt is raised when the user presses Ctrl+C (or the interrupt key) to stop a running program. It is a subclass of BaseException, not Exception, so bare except: clauses will catch it but except Exception: will not.
Why it happens
- •The user manually interrupts a long-running script with Ctrl+C.
- •A test runner or process manager sends SIGINT to the process.
- •An automated script sends an interrupt signal programmatically.
Potential fixes
Catch KeyboardInterrupt explicitly if you need to perform cleanup before exiting. Use a finally block to ensure resources like file handles and network connections are closed regardless of how the program exits. Avoid catching BaseException broadly.
Examples
Code that triggers the error
# User presses Ctrl+C during this loop
import time
while True:
time.sleep(1)
print("Running...")Error output
Running... Running... ^CTraceback (most recent call last): File "app.py", line 3, in <module> KeyboardInterrupt
Fixed code
import time
try:
while True:
time.sleep(1)
print("Running...")
except KeyboardInterrupt:
print("Stopped by user")Practice in English
How would you explain a KeyboardInterrupt to a fellow dev? Choose the right phrase:
"I hit an error...
Ready to practice your English at work?
Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.
Try Lingua-e for free