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:
#some code that might trigger an error
#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: ")
result = 10 / int(num)
print("10 divided by your number is: ", result)
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.
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
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:
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;
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.
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!
Thanks to Namazi Jamal for his contributions in writing this article!