Python: Catch All Errors

In this article, we’ll study how to catch all errors in Python. Additionally, we will also learn how to catch just a single error. To make us understand better, we’ll also take a look at the exception hierarchy. Without further ado, let’s begin!

Catching all errors using “except:”

If you’re looking to catch all errors in your code, try the ‘except:’ statement:

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

The except: statement, simply put captures every single error that can be triggered. This is generally not recommended as capturing specific errors to handle them appropriately is considered best practice, else your teammates will start thinking you have no clue what you are doing so you are quietly sweeping things under the rug!

Let us see what I mean with the help of some examples.

In the following example, we’ll trigger 2 types of exceptions in the same code and see how the except statement handles them both;

num = input("Enter a number: ")

try:
    result = 10 / int(num)
    print("10 divided by your number is: ", result)
except:
    print("An error occured!")
Enter a number: hi
An error occured!

A ValueError was raised in the above code when the int() function tried to convert it into an integer. This was handled by the except block appropriately.

Enter a number: 0

An error occured!

This time, a ZeroDivisionError was raised in the above code when there was an attempt to divide by 0. This was again handled by the except block appropriately.

While catching all the exceptions seems convenient, like we mentioned before it is not considered as good practice as now we don’t know what was the exception that was triggered.

There are other ways to do this too, if you are interested refer to the article below.

3 ways to catch multiple exceptions in a single except clause

If possible your aim should be to group errors by “error-types” and treat each “error-type” differently. Let us see what I mean.

Catching a group of similar exceptions

Catching a group of similar exceptions is pretty simple as shown in the following example

try:
    import ExampleModule
except ImportError:
    print("Error: There was a problem while importing the module!")
Error: There was a problem while importing the module!

The syntax from the above code is:

except <exceptionName>

At first glance, you might think that this program handles a single exception, the ImportError exception class. But the reality is that when we specify an exception, the interpreter will deal with that exception and all its subclasses.

This means that in the example we saw, the except ImportError handles both the ImportError and its subclass, ModuleNotFoundError.

To understand this better, we’ll first have to understand an important idea, “the hierarchy of exceptions”. Let us explore that idea next!

Hierarchy of Exceptions 

We have a big tree of exception classification in Python. It is classified in a way that reflects their natures. This helps us developers in error handling and writing code that is easy to maintain.

Let’s say, for instance, any operating system problem would be classified under the group OSError exception. While on the other hand, any math-related problem would be put into the ArithmeticError group.

Python also takes it a step further and classifies these classes further into subclasses, like how ArithmeticError can further be classified into ZeroDivisionError which only deals with division by zero divisions. 

These groupings of classes and subclasses are what we call the Hierarchy of Exceptions in Python. 

So when we write the following statement in Python;

except <ExceptionA>

We are saying please handle the exception ExceptionA and all of its subclasses!

Note: Did you know that there is no difference between ‘except:’ and ‘except BaseException:’

That’s right, the way way ‘except:’ works is by capturing BaseException (and its subclasses of course) is pretty much all the exceptions in Python.

Refer to the diagram below

Here’s a complete visualization of the whole exception hierarchy:

If you wish to get a better understanding of this Hierarchy, checkout our article on this topic below.

Hierarchy of Exceptions

For the next step in your Python journey I invite you to master some of the most common errors you will run into in your daily life as a Python developer. We have compiled a list of just 7 exceptions that you need to focus on if you wish to gain mastery of Exceptions 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 end this article.

Kudos to you on making it to the end of the article, not many have the patience to do so!

I hope you enjoyed reading this article and found this article helpful!

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

“Exception” Class in Python: A Walk-through!

Python: How to Create a Custom Exception

7 Most Common In-Built Exceptions in Python!

Python: Details contained in an Exception

Hierarchy of Exceptions in Python

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