Python “except:” vs “except Exception as e:”

In this article, let us see the difference between the following 2 lines of code in Python

except:

and

except Exception as e:

While they both can be used to capture a variety of exceptions in Python, there are subtle differences.

For those of you in a hurry, here is a short table showing their similarities and differences!

Don’t worry if the above table does not make sense to you as that was targeted at more experienced programmers who just wanted to refresh their memories. The rest of this article is dedicated to those of you in the first steps of your journey to becoming a Python Craftsman.

By the time you reach the end of this article, I suggest you come back and read this table once more, I assure you it will make much more sense then!

The Fundamentals

Here is a video we made about Exceptions and their place in the programming world. I suggest watching the video to get your fundamentals strong before continuing on with this article!

Now that we have the fundamentals strong, let us get back to the topic and start our discussion by looking at Python’s Hierarchy of exceptions.

Understanding Python’s Hierarchy of Exceptions

I remember the time when I first came across these 2 lines of code in various tutorials and code bases, at first I didn’t understand what was going on in the background until I learned about the hierarchy of exceptions in Python, so that is where we will start our journey today!

All exceptions in Python are derived from the BaseException class. The BaseException class has a subclass called the Exception class. Most of the day-to-day exceptions developers face such as KeyError, AttributeError, TypeError, etc are derived from this class.

You can see the Exception family tree in Python below.

To learn more on how all the different exception classes are organized, head over to our other article below, where we have given a detailed overview about the exception hierarchy.

Hierarchy of Exceptions in Python

Now that we have a basic idea of how the hierarchy works and how some exceptions are a subclass of other exceptions, let’s move on to see how this hierarchy plays a role in understanding the similarities and differences between ‘except:’ and ‘except Exception as e:’!

except:’ vs ‘except Exception as e:’

The “except:” statement works by catching the exceptions under the BaseException class, in other words, it catches all the exceptions.

For the visual learners, all classes highlighted in red are handled by the ‘except:’ statement:

On the other hand, the ‘except Exception as e:’ only catches exceptions under the Exception class. This means that exceptions under other subclasses of the BaseException class such as GeneratorExit or SystemExit won’t be caught.

For the visual learners, all classes highlighted in red are handled by the ‘except Exception as e:’ statement:

Let us see some examples to help hammer away the point home!

Catching an error from the Exception class using just the ‘except’ statement:

try:
    x = 10 / 0
except:
    print("An error occurred in your program!")

OUTPUT

An error occurred in your program!

And here’s catching the same error using the ‘except Exception as e’ method

try:
    x = 10 / 0
except Exception as e:
    print("An error occurred in your program:", e)

OUTPUT

An error occurred in your program!

Looks like both of them worked!

Notice how we can customize the output using the caught exception object and print its message. We can do a lot more using this object and we have written a nice article on this topic that you can find in the link below!

Python: “except Exception as e” Meaning Explained!

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

Next, let’s try to handle an error that is not derived from the Exception class. Let’s try raising an exception from one of the subclasses of the BaseException such as the KeyboardInterrupt exception:

Let us start with the ‘except’ statement:

try:
    raise KeyboardInterrupt
except:
    print("An error occurred in your program!")

OUTPUT

An error occurred in your program!

As you can see the KeyboardInterrupt exception was caught using the “except:” statement and the print statement got executed

Now let’s see how it works out when we use “except Exception as e:”

try:
    raise KeyboardInterrupt
except Exception as e:
    print("An error occurred in your program!")

OUTPUT

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
KeyboardInterrupt

This time our code has crashed with a traceback message and the KeyboardInterrupt was not caught by the except clause.

If you wish to understand how to use this error message to debug your python code like a pro, then here is an excellent article to get you started!

Python: Details contained in an Exception

This clearly shows how using the ‘except Exception as e’ method only works in handling exceptions inherited from the ‘Exception’ class and not from the ‘BaseException’ class.

If you want a tour of the Exception class in python, I invite you to head over to the following article!

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

If you are like me and you prefer clarity over cleverness, then you can use the following code instead of “except:” statement

except BaseException:

This will work the exact same way as the “except” statement

try:
    x = 10 / 0
except BaseException:
    print("An error occurred in your program!")

OUTPUT

An error occurred in your program!

As you can see the KeyboardInterrupt exception was caught using the “except BaseException:” statement and the print statement got executed.

In conclusion, it is best to use “except:” or “except BaseException:” when you want to catch any and all types of exceptions and it is best to use “except Exception as e” when you want to catch commonly faced exceptions.

Here’s the table from earlier, I hope by now you undestood the difference between these 2 similar statements and the table makes more sense!

And with that, I will end this article.

Congratulations on making it to the end of the article, not many have the perseverance to do so!

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

Exceptions in Python: Explained for Beginners!

Python: Details contained in an Exception

7 Most Common In-Built Exceptions in Python!

Python: Catch Exception and Print

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