Catch all errors except KeyboardInterrupt

In this article, we will learn how to catch all the errors in Python except KeyboardInterrupt. We will also be learning this alongside examples to make us understand better. Without further ado, let’s begin!

First things first, let’s refresh our memories on the hierarchy of exceptions, refer to the following chart:

What we’re trying to do now is to catch all the exceptions above (except the KeyboardInterrupt exception). 

For now, let’s see how to catch all the exceptions:

As we can see from the flowchart, the BaseException class seems to be the parent class for all the exceptions. So catching means we’re also catching all of its child class exceptions as well.

Python allows us to do this by using the ‘except:’ statement:

try: 
    #some code that might cause an error
except: 
    #error handling code

Now our program will handle any error that will be triggered, including the KeyboardInterrupt. 

To avoid this, we can catch and treat it separately, before the except: statement:

try: 
    #some code that might cause an error
except KeyboardInterrupt:
    #error that handles KeyboardInterrupt
except: 
    #error handling code

This is obviously because if the except KeyboardInterrupt: was after the except: statement, the except: would catch and treat it like any other error which we don’t want to happen.

The KeyboardInterrupt exception allows the user to manually interrupt the program. If you catch this error you are stopping your code from exiting after a request from the user, so we should do whatever cleanup is needed rather quickly and reraise the KeyboardInterrupt:

try: 
    #some code that might cause an error
except KeyboardInterrupt:
    # do necessary cleanup
    raise KeyboardInterrupt
except: 
    #error handling code

Note: You can also just write ‘raise’ instead of ‘raise KeyboardInterrupt’ in the above program

This way the program handles any error and also allows the user to exit manually via the KeyboardInterrupt:

Let’s finish things off with an example:

try:
    dividend = int(input("Please enter the dividend: "))
    divisor = int(input("Please enter the divisor: "))
    result = int(dividend ) / int(divisor)
    print("The answer is", result)
    print("Exiting the program...")
except KeyboardInterrupt:
    print("Exiting the program")
    raise
except:
    print("Oops! A problem has occurred. Please try again.")
    print("Exiting the program...")

Here are various outputs depending on the user’s input:

Please enter the dividend: 10
Please enter the divisor: 5
The answer is 2.0
Exiting the program...
Please enter the dividend: 10
Please enter the divisor: 0
Oops! A problem has occurred. Please try again.
Exiting the program...
Please enter the dividend: hi
Oops! A problem has occurred. Please try again.
Exiting the program...
Please enter the dividend: ^CExiting the program
Traceback (most recent call last):
  File "/home/main.py", line 2, in <module>
    dividend = int(input("Please enter the dividend: "))
KeyboardInterrupt

Also it is worth noting that KeyboardInterrupt is not one of the most common Exceptions that you will deal with in your daily life as a Python developer. Instead, you need to focus on 7 other errors mentioned in the article below if you wish to gain mastery in Python!

7 Most Common In-Built Exceptions in Python!

If you are a visual learner here is a YouTube video that we made on that same topic!

And with that, let’s wrap up this article!

Shout out to you for making it this far! Not many have the patience and curiosity that you have!

I hope you enjoyed reading this article and found it useful!

Feel free to share it with your friends and colleagues!

If your thirst for knowledge has not been quenched yet, here are some related articles that might spark your interest!

Related Articles

Python: Details contained in an Exception

Print just the message of an exception

Python: Printing Exception Type

Python: Print StackTrace on Exception!

Exceptions in Python: Everything You Need To Know!

Thanks to Namazi Jamal for his contributions in writing this article!

Photo of author
Editor
Balaji Gunasekaran
Balaji Gunasekaran is a Senior Software Engineer with a Master of Science degree in Mechatronics and a bachelor’s degree in Electrical and Electronics Engineering. He loves to write about tech and has written more than 300 articles. He has also published the book “Cracking the Embedded Software Engineering Interview”. You can follow him on LinkedIn