Introduction to Python KeyboardInterrupt
We already know the exceptions and how to handle them in Python. In layman’s language, exceptions are something that interrupts the normal flow of the program. Similarly, the KeyboardInterrupt exception is a Python exception that is raised when the user or programmer interrupts the normal execution of a program. The interpreter in Python regularly checks for any interrupts while executing the program. In Python, the interpreter throws a KeyboardInterrupt exception when the user/programmer presses the ctrl – c or del key either accidentally or intentionally.
Syntax:
As observed in the example above, the KeyboardInterrupt exception is a standard exception used to handle keyboard-related issues. There is no specific syntax unique to the KeyboardInterrupt exception in Python; it is handled like any other exception using the try-except block within the code. The code that might generate the exception is placed within the try block, and it is either explicitly raised using the ‘raise’ keyword or automatically raised by the Python interpreter. To handle the exception and perform desired actions, specific code is written within the except block.
try:
# code that can raise the exception
# raising this exception is not mandatory
raise KeyboardInterrupt
except KeyboardInterrupt:
# code to perform any specific tasks to catch that exception
How does KeyboardInterrupt Exception work in Python?
One of the most frustrating aspects of working with Python is that it terminates the program when the user presses Ctrl-C, whether intentionally or accidentally. This can be a significant issue, especially when dealing with tasks such as processing bulk data, retrieving records from a database, or executing large programs that handle multiple tasks simultaneously. This exception works very simply, like other exceptions in Python. The only thing about this exception is that it is user generated, and the computer is not involved in raising it. In order to understand the working of KeyboardInterrupt exception in Python, let’s understand the below-written code first.
Code:
try:
# code inside the try block which can cause an exception
# taking the input ‘name’ from the user
name = input('Enter the name of the user ')
# writing the different exception class to catch/ handle the exception
except EOFError:
print('Hello user it is EOF exception, please enter something and run me again')
except KeyboardInterrupt:
print('Hello user you have pressed ctrl-c button.')
# If both the above exception class does not match, else part will get executed
else:
print('Hello user there is some format error')
In the above code:
- First, the code inside the try block is executed.
- If the user presses the ctrl – c, an exception will be raised, and execution of the rest of the statements of the try block is stopped and will move the except block of the raised exception.
- If no exceptions occur within the try block, the execution continues normally, and no statements within the ‘except’ block are executed.
- If an exception is raised but does not match the class name specified in the exception handler following the ‘except’ keyword, the program will search for a corresponding catch block outside the inner try block to handle it. If a suitable catch block is not found, the program will exit with a standard Python message.
How to Avoid KeyboardInterrupt Exceptions in Python?
- There is no such way to avoid the KeyboardInterrupt exception in Python, as it will automatically raise the KeyboardInterrupt exception when the user presses the ctrl – c. There are a few things that we can do in order to avoid this.
- As we all know, that final block is always executed. So if the exception is raised and we are tangled in some infinite loop, then we can write a clean code in the final block (which will get executed in every case), which can help us to backtrack the situation.
- It depends on how the programmer he/she codes to avoid this situation, as every programmer has a different way of thinking and hence coding.
Example of Python KeyboardInterrupt
Given below is the example mentioned. General output when the user presses the ctrl – c button.
Code:
try:
# code inside the try block which can cause an exception
# taking the input ‘name’ from the user
name = input('Enter the name of the user ')
# writing the different exception class to catch/ handle the exception
except EOFError:
print('Hello user it is EOF exception, please enter something and run me again')
except KeyboardInterrupt:
print('Hello user you have pressed ctrl-c button.')
# If both the above exception class does not match, else part will get executed
else:
print('Hello user there is some format error')
Output 1:
When the user presses the ctrl -c button on asking the username by the program, the below output is generated.
Explanation:
In the above output, the print statement written for the KeyboardInterrupt exception is displayed as the user presses the ctrl – c, which is a user interrupt exception.
Output 2:
When the user presses the ctrl – d button on asking for the username by the program, the below-given output is generated.
Explanation:
In the provided output, when the user presses the Ctrl-D button, indicating the end of the file, a print statement under the EOF exception class is displayed. This signifies that the specified exception class is checked when the exception occurs.
Conclusion
The above article provides a clear explanation of the KeyboardInterrupt exception in Python. For any programmer, be it a newbie or an expert, it is very important to understand every type of exception in detail to deal with them accordingly and write a program efficiently (able to handle any kind of such situation).
Recommended Articles
This is a guide to Python KeyboardInterrupt. Here we discuss how KeyboardInterrupt exception works and how to avoid KeyboardInterrupt exceptions in Python with respective examples. You may also have a look at the following articles to learn more –