Introduction to Python KeyboardInterrupt
As we already know what the exceptions are and how to handle them in Python. In layman language, exceptions are something that interrupts the normal flow of the program. Similarly KeyboardInterrupt is a python exception which is generated when the user/programmer interrupts the normal execution of a program. Interpreter in python checks regularly for any interrupts while executing the program. In python, interpreter throws KeyboardInterrupt exception when the user/programmer presses ctrl – c or del key either accidentally or intentionally. KeyboardInterrupt exception inherits the BaseException and similar to the general exceptions in python, it is handled by try except statement in order to stop abrupt exiting of program by interpreter.
Syntax:
As seen above, KeyboardInterrupt exception is a normal exception which is thrown to handle the keyboard related issues. There is no such specific syntax of KeyboardInterrupt exception in Python, it is handled in the normal try and except block inside the code. Code which can cause the error is placed inside the try block with the ‘raise’ keyword to raise that exception or the python interpreter automatically raises it. To catch the exception and perform desired tasks, special code inside the except block is written.
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 annoying things while working with python is that it exits the program once the user presses ctrl – c either intentionally or mistakenly which is a big problem when the bulk data is getting processed like retrieving records from database, handling, executing a big program handling many tasks at a time, etc. This exception works in a very simple manner like other exceptions in Python. Only thing about this exception is that it is user generated and there is no involvement of the computer in raising it. In order to understand the working of KeyboardInterrupt exception in Python, lets 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, 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 arise in the try block, then the execution continues in a normal manner but no ‘except’ block statements are executed.
- If the exception is raised but does not match with the class name of the exception handler present after the except keyword, it will start looking for the respective catch block to handle it outside the inner try block. If not found, then it will exit the program with the normal 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 few things that we can do in order to avoid this.
- As we all know that finally 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 finally block (which will get executed in every case) which can help us to backtrack the situation.
- It totally depends on the programmer how he/she codes in order to avoid this situation as every programmer has a different way of thinking and hence coding.
- Some add a flag or variable which gets incremented when the user clicks on the ctrl – c button or some programmers creates a separate function which takes some extra input or keeps track of the user pressing ctrl- c keys and responds accordingly.
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 the username by the program, below given output is generated.
Explanation:
In the above output, a print statement written under the EOF exception class is displayed as the user presses the ctrl – d button which indicates the end of file. This indicates that the desired exception class is searched when the exception arises if catched in the code, the following block is executed.
Conclusion
Above article clearly explains what the KeyboardInterrupt exception is, how it is raised and is handled in Python. KeyboardInterrupt exception as the name indicates is a simple exception which is raised when the program is interrupted by the user keyboard. For any programmer be it a newbie or an expert it is very important to understand each and every type of exception in detail in order to deal with them accordingly and write a program efficiently (able to handle any kind of such situations).
Recommended Articles
This is a guide to Python KeyboardInterrupt. Here we discuss how does KeyboardInterrupt exception work, how to avoid KeyboardInterrupt exceptions in Python with respective examples. You may also have a look at the following articles to learn more –
40 Online Courses | 13 Hands-on Projects | 215+ Hours | Verifiable Certificate of Completion
4.8
View Course
Related Courses