How to Handle Keyboard Interrupt in Python: Simple Guide
KeyboardInterrupt exception using a try-except block. This lets your program stop gracefully when you press Ctrl+C instead of crashing.Why This Happens
When you press Ctrl+C while a Python program is running, it raises a KeyboardInterrupt exception. If you don't catch this exception, the program stops immediately and shows an error message.
while True: print("Running...")
The Fix
Wrap your code in a try block and catch KeyboardInterrupt in an except block. This way, you can print a message or clean up before the program ends.
try: while True: print("Running...") except KeyboardInterrupt: print("Program stopped by user.")
Prevention
Always use try-except KeyboardInterrupt when running loops or long tasks to allow graceful exits. This avoids abrupt stops and lets you save data or release resources properly.
Use clear messages to inform users the program stopped by their action.
Related Errors
Other exceptions like SystemExit or EOFError can also stop programs unexpectedly. Handling KeyboardInterrupt is specific to user interrupts (Ctrl+C).
For cleanup on any exit, use finally blocks or atexit module.