Accessing The Caught Exception Object In The “except” Block In Python!

In this article, let us learn how to access the exception object that we have just caught in the “except” block and see some useful ways we can use that object to help make our code more robust and professional!

I remember the first time I was learning the try-except blocks and exception handling in Python, one thing that always intrigued me was the object that the except blocks catch. Particularly the following questions popped up in my mind

  • How can I access the exception object?
  • What information is hidden inside those objects?
  • How can I make use of that information to make my code better?

This article is all about answering the above questions!

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 by answering the following question

How to access the caught exception object?

As you might already know, in Python, whenever there’s an error or an exception, it can be handled by using the try-except block like this:

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

In order to access the object being caught in a given “except” block, we need to assign this caught exception to a variable using the keyword ‘as’:

Here’s the syntax for that:

try:
    # error containing code 
except <exception type> as <variable name>:
    # error handling code

For instance, using the previous example again:

try:
    print(1/0)
except ZeroDivisionError as e:
    print("Error Name:", e)
Error Name: division by zero

Here printing the variable ‘e‘ gave us the string “division by zero“, pretty cool right?

We can already see how useful this will be as we can customize the error output to make it more user-friendly.

If you still get an “incomplete” feeling after reading the above explanation, I invite you to check out the video we made on that topic!

Now we can do a lot of things with this object since it has access to the exception’s properties, let us next see what information is hidden inside those objects!

What information is hidden inside those objects?

When you encounter an error in Python, you get a message packed with several details about the error.

The technical name of the entire error message is “Traceback” and its 3 main parts are

  1. Stack Trace – helps you find in which part of the code the error occurred 
  2. Exception Name – Says what type of exception has occurred &
  3. Exception message – A short message explaining what the error was.

The figure below shows all 3 parts of the Error Message.

Details contained in an Exception

If this short explanation leaves you confused don’t worry as this was aimed at people who are already familiar with the concepts and are just looking to refresh their memories.

We have an entire article dedicated to this topic which you can find in the link below!

Python: Details contained in an Exception

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

Now that we have understood the inner blueprint of the exception object, the next step is to make use of the information to make our code better. Let us go ahead and see how to do that next!

How can we make use of that information to make our code better?

One way we can make use of them is to print them out! I suggest watching the following video we made to get a quick primer on how to go about printing exceptions.

This video shows how to print the exception message. Though it is extremely useful, in my personal experience, sometimes all we need is the Exception Type, while other times Exception Name is useful and in some other occasions the stack-trace can come in real handy!

Let’s start by looking at how we can print the exception type.

Printing Exception Type

We can use the type() function to identify the class of the object and print it using the syntax below.

try:
  # code that might cause an exception
except Exception as e:
  print(type(e))
try:
    300 / 0
except Exception as e:
    print(type(e))
<class 'ZeroDivisionError'>

If these examples feel a bit advanced, I highly recommend reading our full article on printing the exception type in the link below.

Python: Printing Exception Type

Next, let us see how we can print the exception message

Printing Exception Message

To print the exception message, all we need to do is simply give the exception object “e” to the in-built print() function!

try:
    # some code that might raise an exception
except Exception as e:
    print(e)
try:
  print(1/0)
except Exception as e:
  print(e)
division by zero

Again, if these examples feel a bit advanced, I highly recommend reading our full article on printing the exception message in the link below.

Print just the message of an exception

There I have also explained how this magic of “giving the object to print( ) gets us the exception message” works.

Next, let us see how we can print the exception stack-trace.

Printing Exception Stacktrace

Printing the stack-trace becomes straightforward when we store it in a variable and print it line by line:

try:
   # some code that might raise an exception
except ZeroDivisionError as e:
    stack_trace = traceback.format_tb(sys.exc_info()[2])
    for line in stack_trace:
        print(line)

For example, look at the following code. A function inside another function triggers the exception:

import traceback
import sys
def func_with_error():
    x = 1/0
def my_func():
    func_with_error()

Now if we use the except handling method from earlier:

try:
    my_func()
except ZeroDivisionError as e:
    stack_trace = traceback.format_tb(sys.exc_info()[2])
    for line in stack_trace:
        print(line)
  File "/home/main.py", line 9, in <module>
    my_func()

  File "/home/main.py", line 6, in my_func
    func_with_error()

  File "/home/main.py", line 4, in func_with_error
    x = 1/0

Again, if this explanation and examples feel a bit advanced, I highly recommend reading our full article on printing the exception stack-trace in the link below.

Python: Print StackTrace on Exception!

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