KeyboardInterrupt — Easy Examples
Raised when the user presses Ctrl+C
Triggering KeyboardInterrupt
How KeyboardInterrupt is raised and how to catch it.
python
# Triggering and catching KeyboardInterrupt try: raise KeyboardInterrupt("simulated interrupt") except KeyboardInterrupt as e: print(f"Caught KeyboardInterrupt: {e}") print(f"Type: {type(e).__name__}")
KeyboardInterrupt is raised when raised when the user presses ctrl+c. Always catch specific exceptions rather than bare except clauses.
Handling KeyboardInterrupt
Basic error handling pattern for KeyboardInterrupt.
python
# Safe handling pattern def safe_operation(): try: raise KeyboardInterrupt("simulated interrupt") except KeyboardInterrupt: print("Operation failed gracefully") return None result = safe_operation() print(f"Result: {result}")
Wrapping risky operations in try/except blocks prevents your program from crashing.
Want to try these examples interactively?
Open Easy Playground