← Back to Error Guide
KeyboardInterrupt

How to Fix KeyboardInterrupt

Raised when the user interrupts program execution, usually by pressing Ctrl+C.

What is KeyboardInterrupt?

A KeyboardInterrupt error occurs when a running Python program is interrupted by the user, typically by pressing Ctrl+C (or Ctrl+Break on some systems) in the terminal. This raises the KeyboardInterrupt exception, which can be caught and handled by the program. If not handled, the program will terminate.

Common Causes

How to Fix

  1. Wrap your main code in a try-except block to catch KeyboardInterrupt and handle it gracefully.
  2. Ensure that any cleanup operations (like closing files or saving progress) are performed in the except block or in a finally block.

Wrong Code

# Running this script and pressing Ctrl+C will immediately terminate it without cleanup.
while True:
    pass

Correct Code

# This script handles KeyboardInterrupt and performs cleanup before exiting.
try:
    while True:
        pass
except KeyboardInterrupt:
    print('Interrupted by user. Cleaning up...')

More Python Error Guides