Exceptions are run-time errors that a program encounters during its execution. The “KeyboardInterrupt” exception is one of them which can cause the system to crash. Exception Handling is the process of dealing with such exceptions or events to prevent them. In this tutorial, we will learn How to catch a KeyboardInterrupt in Python using different methods.
If you want to learn more about Python Programming, visit Python Programming Tutorials.
What is a “KeyboardINTERRUPT” EXCEPTION ?
When the user interrupts the program manually by pressing ctrl + c or ctrl + z commands of keyboard, a KeyboardInterrupt exception is raised. Sometimes, the user unintentionally presses the keyboard keys. Interrupting the kernel of jupyter notebook can also raise keyboardinterrupt error which causes the program to halt suddenly in the middle of execution.
Consider an example in which the value of count is incremented on every iteration of an infinite while loop. Press the keyboard shortcut Ctrl + C, you will observe pause that the programme will stop executing. The output screen will display the “KeyboardInterrupt” message.
count = 0 while True: print(count) count += 1
158861 158862 158863 158864 158865 Process finished with exit code -1073741510 (0xC000013A: interrupted by Ctrl+C)
How to catch a keyboard interrupt?
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")
Keyboard interrupt exception caught
In this article, we have discussed keyboardinterrupt exception in detail and different methods by which you can catch these exceptions. Exception handling is very important to prevent halts and normal running of programs. For any query, contact us. Let us know your feedback about this article.