How to catch a KeyboardInterrupt in Python

Exceptions are errors that occur during the execution of a program. One such exception is the “KeyboardInterrupt” exception, which can cause a program to crash. Exception handling is the process of handling these exceptions or events to prevent program failures. In this tutorial, we will explore different methods to catch a KeyboardInterrupt exception in Python and handle it effectively.

If you want to learn more about Python Programming, visit Python Programming Tutorials.

What is a “KeyboardInterrupt” Exception?

A “KeyboardInterrupt” exception is raised when a user manually interrupts a program by pressing keyboard commands such as Ctrl+C or Ctrl+Z. This exception is commonly encountered when the user unintentionally triggers it or when they want to interrupt the execution of a program or code cell manually.

In Jupyter Notebook, a keyboard interrupt exception can occur by pressing the stop button or using the keyboard shortcut Ctrl+C. Similarly, in Google Colab, pressing the stop button or using the keyboard shortcut Ctrl+M I can raise a keyboard interrupt exception. These actions send a signal to the Python interpreter running in the Jupyter Notebook or Google Colab environment, causing it to raise a KeyboardInterrupt exception. Interrupting the kernel in Jupyter Notebook can also result in a KeyboardInterrupt error, abruptly halting the program’s execution.

Consider an example where the value of the variable “count” is incremented within an infinite while loop. The keyboard interrupt can be generated by manually interrupting the infinite loop using the keyboard shortcut Ctrl+C. When the program is running and continuously printing the value of count, if you press the keyboard shortcut Ctrl+C, you will observe that the program will pause and raise a KeyboardInterrupt exception.

#Program to demonstrate how a KeyboardInterrupt exception is generated by pressing Ctrl+C or a similar keyboard command.

count = 0

#infinite while loop
while True:

     #Print the current value of count
    print(count)
    
     # Increment count by 1 in each iteration
    count += 1

Output

---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-1-144686312c83> in <cell line: 6>()
      7 
      8      #Print the current value of count
----> 9     print(count)
     10 
     11      # Increment count by 1 in each iteration

3 frames
zmq/backend/cython/socket.pyx in zmq.backend.cython.socket.Socket.send()

zmq/backend/cython/socket.pyx in zmq.backend.cython.socket.Socket.send()

zmq/backend/cython/socket.pyx in zmq.backend.cython.socket._send_copy()

/usr/local/lib/python3.10/dist-packages/zmq/backend/cython/checkrc.pxd in zmq.backend.cython.checkrc._check_rc()

KeyboardInterrupt: 

The KeyboardInterrupt exception is specifically designed to handle cases where the user wants to interrupt the execution of a program or code cell manually.

Using try and Except block to catch keyboard interrupt exception

Exception handling enables programs to continue running without being interrupted. Keyboard interrupt exceptions can be readily handled with try-except blocks. Place the code that might result in a KeyboardInterrupt exception inside a try block. Use the syntax except error with error as KeyboardInterrupt in the except block to catch the exception.

try:
     raise KeyboardInterrupt
except KeyboardInterrupt:
     print("Keyboard interrupt exception caught")

Output:

Keyboard interrupt exception caught

When you run this code, it will raise the KeyboardInterrupt exception immediately after encountering the raise KeyboardInterrupt line. As a result, the program will not proceed to the print() statement, and instead, it will be caught by the except block, which prints the specified message.

By using the syntax except KeyboardInterrupt as error, you catch the exception and can perform specific actions or display custom messages. In the try block, you place the code that might raise the KeyboardInterrupt exception. Then, in the except block, you specify the exception you want to catch, which in this case is KeyboardInterrupt. Here’s an updated version of the above example of an infinite while loop using try except block:

#Example code to catch KeyboardInterrupt exception using try-except block.
count = 0

try:
    while True:
        print(count)
        count += 1
except KeyboardInterrupt:
    print("Keyboard interrupt exception caught")

Output:

0
1
2
3
4
5
Keyboard interrupt exception caught

When running this code, on pressing Ctrl+C, the program will catch the KeyboardInterrupt exception and print the message “Keyboard interrupt exception caught” before exiting the loop.

Use Signal Handlers to Catch the KeyboardInterrupt Error in python

In Python, you can use signal handlers to catch the KeyboardInterrupt error. The signal module allows us to set up and handle operating system signals, including the SIGINT signal, which is raised when the user interrupts the program.

This code demonstrates how to handle the KeyboardInterrupt exception (raised when the user presses Ctrl + C) using a signal handler in Python.

import signal
import time

def signal_handler(sig, frame):
    print("\nKeyboard interrupt exception caught")
    time.sleep(2) 
    print("Exiting the program.")
    exit(0)

# Register the signal handler for SIGINT (Ctrl + C)
signal.signal(signal.SIGINT, signal_handler)


while True:
  #Insert your code here
  print("Code Running!...")
  time.sleep(1)

Output:

Code Running!...
Code Running!...
Code Running!...
Code Running!...
Code Running!...
Code Running!...
Code Running!...

Keyboard interrupt exception caught
Exiting the program.
Code Running!...
Code Running!...
Code Running!...
Code Running!...
Code Running!...
Code Running!...

Keyboard interrupt exception caught
Exiting the program.
Code Running!...
Code Running!...
Code Running!...
Code Running!...
Code Running!...
Code Running!...
Code Running!...

Keyboard interrupt exception caught
Exiting the program.
Code Running!...

In this example, we have a simple infinite loop that prints a message “Code Running!…” every second. The signal handler is registered to catch the SIGINT signal (Ctrl + C). If you run this code and then press Ctrl + C, the signal handler will be called, and the message “Keyboard interrupt exception caught” will be printed. The program will then sleep for 2 seconds meanwhile then you can simulate some cleanup operations before exiting the program when a KeyboardInterrupt error occurs.

Consider a simple number guessing game in Python that uses a signal handler to catch the KeyboardInterrupt exception (raised when the user presses Ctrl+C) and allows the user to quit the game. In this game, the user is asked to guess a randomly generated number between 1 and 10. If the user enters a non-numeric value, they are prompted to enter a valid number. If the user guesses the correct number, they receive a congratulatory message and their score is incremented. If the user interrupts the game by pressing Ctrl+C, the signal handler catches the KeyboardInterrupt exception, displays a message.

import signal
import random

def signal_handler(sig, frame):
    print("Keyboard Interrupt exception raised. Try Again. ")
    exit(0)

# Set the signal handler for SIGINT (Keyboard interrupt)
signal.signal(signal.SIGINT, signal_handler)

def play_game():
    score = 0
    while True:
      try:
        num = random.randint(1, 10)
        guess = int(input("Guess the number between 1 and 10: "))         
        if guess == num:
          print("Congratulations! You guessed it right.")
          score += 1
        else:
          print(f"Oops! The number was {num}. Try again.")
      except ValueError:
        print("Invalid input. Please enter a valid number.")
  
if __name__ == "__main__":
    print("Welcome to the Number Guessing Game!")
    play_game()

Output:

Welcome to the Number Guessing Game!
Guess the number between 1 and 10: 4
Oops! The number was 10. Try again.
Guess the number between 1 and 10: 6
Oops! The number was 1. Try again.
Keyboard Interrupt exception raised. Try Again.
Keyboard Interrupt exception raised. Try Again.
Keyboard Interrupt exception raised. Try Again.
Keyboard Interrupt exception raised. Try Again. 
Keyboard Interrupt exception raised. Try Again.
Guess the number between 1 and 10: 3
Oops! The number was 1. Try again.

The above program continues running until you restart the kernel. In the above example, you can also use the try-except block to catch keyboard interrupt exception.

Conclusion

In this article, we have thoroughly explored keyboard interrupt exceptions and various methods to catch them effectively in Python. Exceptions are errors that occur during the execution of a program, and a “KeyboardInterrupt” exception is one such type that is raised when the user manually interrupts the program using keyboard commands. Exception handling is crucial to ensure the smooth execution of programs and avoid abrupt halts. We’ve covered two different approaches to handle Keyboard Interrupt exceptions: using try-except blocks and signal handlers. By using these techniques, you can make your programs more robust and user-friendly. If you have any queries or need further assistance, feel free to reach out. Your feedback on this article is valuable to us as we continue to provide comprehensive Python programming tutorials. Happy coding!.

Leave a Comment

Your email address will not be published. Required fields are marked *