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.
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
How to fix it
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.
Fixed code
import time
try:
while True:
time.sleep(1)
print("Running...")
except KeyboardInterrupt:
print("Stopped by user")Related errors
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