Python: “except Exception as e” Meaning Explained!

In this article, we’ll take a look at the “except Exception from e” statement. We will learn what it means exactly and see how to use them in our programs.

For those of you in a hurry here is the short version of the answer.

“except Exception as e”: In a Nutshell

The ‘except Exception as e’ statement is used with try-except statements to capture any exception raised in the try block and store it in an object named e.

try:
    #code that might raise an exception
except Exception as e:
    #code that handles the error

By catching the exception and storing it in an object, we can access the attributes of the caught exception. By attributes here I mean the data contained inside the exception object.

If you wish to learn what details are contained in an exception and how to make use of them, here is an excellent article covering all the available options.

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

As a quick example, here is how you can print the error message that came as part of the caught exception object.

try:
    x = y + 3
except Exception as e:
    print(e)
name 'y' is not defined

Here we forgot to define the variable y, which resulted in an exception. This exception was caught by our statement except Exception as e: and the message contained within is printed out.

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

Don’t worry if the above answer 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 summary once more, I assure you it will make much more sense then!

“except Exception as e”: A Thorough Look!

I remember the time when I first came across the statement “except Exception as e”, it felt like I just heard a spell that does some magic in the background. As my journey went on and my expertise in Python improved, I finally understood what it meant, and this article is all about getting you to the same level of understanding!

Meaning of “except Exception as e“

The ‘except Exception as e’ is a statement commonly used in exceptional handling.

try:
    #code that might cause an error
except Exception as e:
    #error handling code

To break it down

  • except: keyword to catch raised exceptions
  • Exception: the class name of the Exception class in Python
  • as: keyword to assign an object to a variable
  • e: the variable to which the Exception object is assigned to

So, what this does is, when it catches the exception raised in the try block, it stores the Exception object in a variable named ‘e’ .

In other words, this object, ‘e’ now represents the caught exception and contains all its properties and behaviors.

The reason the Exception class is used in this statement because all exceptions in python are derived from the Exception class, so it can catch all errors like TypeError, KeyError, etc.

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!

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

Since all exceptions are inherited from the Exception class, developers use this statement “except Exception as e” as a cool trick to catch more than one exception using a single except clause during development stages.

If you wish to catch a specific group of exceptions instead of everything, you can do that using the syntax mentioned in the following article.

Python catch multiple exceptions

If you do not care about accessing the attributes of the caught exception, you can also catch all possible exceptions using the following lines of code.

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

The former method ‘except:’ will handle or deal with all types of exceptions, whereas the latter method ‘except Exception as e’ catches all exceptions other than BaseException or the system exceptions SystemExit, KeyboardInterrupt, and GeneratorExit.

If you wish to catch even SystemExit, KeyboardInterrupt, and GeneratorExit and store the value into a variable, you can use

try:
    #code that might cause an error
except BaseException as e:
    #error handling code

You won’t find any professional writing code like shown above as it is generally considered a bad practice to handle anything which is directly not derived from an exception class.

For example, the user generally expects “Ctrl+C” key combination to generate a KeyboardInterrupt to exit the program, handling it in any custom way is just going to confuse people for no reason.

If you wish to capture all exceptions except keyboard interrupts, you can do that via the syntax explained in the following article.

Catch all errors except KeyboardInterrupt

If you want, you can also narrow down the specific exception type you wish to catch by specifying the name of the Exception as shown below.

try:
    print(1/0)
except ZeroDivisionError as e:
    print("You cannot divide a number by 0!")

OUTPUT

You cannot divide a number by 0!

Here only exceptions of type “ZeroDivisionError” are caught, if any other exception is raised from the try block, you won’t be able to catch them.

try:
    raise ModuleNotFoundError
except ZeroDivisionError as e:
    print("You cannot divide a number by 0!")

OUTPUT

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    raise ModuleNotFoundError
ModuleNotFoundError

As you can see, we ended up with a Traceback instead of our custom message!

If you wish to learn more about ModuleNotFoundError, I invite you to read our comprehensive article on that topic.

ModuleNotFoundError: A Step By Step Troubleshooting Guide!

You can also get the exception type, the stack trace, etc from the exception object. If you wish to learn more here is an article on that exact topic!

Python: Details contained in an Exception

For visual learners out there we have also made an interesting video on that topic!

If you are not familiar with what raise statement does, we have recently written another article on that topic, I suggest setting aside 10mins to read that one to get upto speed!

Python: “raise exception from e” Meaning Explained!

Next let us have a quick look at a closely related statement except Exception

except Exception” vs “except Exception as e

Consider the code below.

try:
    x = y + 3
except Exception as e:
    print(e)

This will result in the following output

name 'y' is not defined

Here we forgot to define the variable y, which resulted in an exception. This exception was caught by our statement except Exception as e: and the message contained within is printed out.

But if we now use just except Exception:

try:
    x = y + 3
except Exception:
    print("Some Error occurred")

All we get is the following output

Some Error occurred

As we don’t have access to the actual Exception object that was raised in the try block, we cannot derive any custom message in our except block.

Hence the difference between the two is simple, without including the sentence “as e”, the caught object is not stored as an exception. So the statement ‘except Exception’ will simply catch any exception and that’s it, whereas the statement ‘except Exception as e’ will catch and store the exception into an object named e.

In other words, the downside of this variant is that after catching the exception, we cannot do any custom action!

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

This 2 statements are also in a way closely related to one another. Their subtle differences are explained in the following article.

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

Conclusion

Below is a 2-line summary of the entire discussion above!

except Exception as e statement is used to catch any raised exception in the try block and store that into an object named e, so that its attributes can be utilized.

embeddedinventor.com

And that’s a wrap, dear readers!

Congratulations for making it till 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 have not been quenched yet, here are some related articles that might spark your interest!

Related Articles

Mutable and Immutable Data Types in python explain using examples

Python: Print StackTrace on Exception!

Exceptions in Python: Explained for Beginners!

Python: Details contained in an Exception

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