Python: Printing Exception Type

In this article we will learn how to print the “type” of an exception, that is the class name to which a given exception belongs to.

Have you ever had your code crash and you were having difficulty debugging that and you said to yourself “If only I can print the damn Exception’s type I can easily fix this bug!” If you are in a similar situation then this article is for you!

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

Printing Exception Type: The Recipe

Printing the exception type from an exception that pops up is pretty simple.

Let’s see it step by step

Step#1: Catch the exception – We’ll need to first catch an exception duh! We can make use of the try – catch block provided by Python to do the same as shown below.

try:
  # code that might cause an exception
except Exception as e:
  # catch the exception here and store in a variable, such as e  here

Step#2: Use the type() function to identify the class of the variable (which is the object we caught here) and print it:

try:
  # code that might cause an exception
except Exception as e:
  print(type(e))

Let’s see an example on how to apply the above steps

try:
    300 / 0
except Exception as e:
    print(type(e))

OUTPUT:

<class 'ZeroDivisionError'>

It is as simple as that!

But that is not all, there is more!

The rest of the article explains

  • how to print just “ZeroDivisionError” instead of “<class ‘ZeroDivisionError’>”
  • how to use the exception type to solve bugs
  • what situations this recipe can be useful

along with various interesting information about the exception class!

I suggest setting aside 10 mins to read till the end of the article to get a much deeper understanding of this topic, as gaining a good deep understanding is very essential on your journey to become a Python craftsman!

Printing Exception Type, a detailed look

No matter how bothersome “Exceptions” are, they are inevitable. That is why it is all the more important to learn how to deal with them.

Let’s start with a quick refresher and see what “Exceptions” really are using a simple analogy

Exceptions, What are they?

If you fill your car’s fuel tank with water instead of gas, the engine will have no idea what to do with it and the engine will simply refuse to run.

Similarly, when the “Python interpreter” (the engine) does not know what to do with the “data” (water) that we gave it, the program will get stuck. The Exception object is just an error report generated by the interpreter giving us clues on

  • what went wrong? and
  • where in the program the problem is?

Sure there is more to Exception than that, but their main use is to give us clues. So the next time when you think about exceptions, think of a them as clues to solve an issue!

If you feel that your basics could use some boosting, I suggest reading the following article

Exceptions in Python: Everything You Need To Know!

Also to get a quick primer on how to go about printing exceptions, I suggest watching the following video

Now that we have covered the basics, next lets try and answer the question “Why do we need the “type” of an Exception?

Understanding why we need to know the “type” of an Exception

If we can predict “where” in our code an exception might be produced/raised, then we can prevent the code from crashing using the try-except blocks. But “where” is not enough, we need to know “what” the problem is, so that we can find away to work with that.

There are several types of exception, each of its own unique type for unique scenarios.

For example, like we saw earlier,

  • if you divide a number by zero you’ll be looking at ZeroDivisionError in your screen.
  • If you try to invoke or access a key that doesn’t exist in your dictionary, you’ll be facing a KeyError.

Once you know the type, your battle for solving the bug is already half over! You can simply google the type and in 20 mins, you will already be able to guess where the issue is in your code!

As you might already know, when we encounter an error while running your code from the command line, we will see an error message which will look something like this:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    print(1/0)
ZeroDivisionError: division by zero


As we can see, the error message seems to contain a lot of details for us to unpack (Python: Details contained in an Exception). But main clue is placed in the first part of the last line:

ZeroDivisionError

Alright, but what if you are not the one running your script, what if it is a client or a friend who is not so tech-savvy? For them this error message is pure gibberish and they will not be able to help you get the Exception type.

In such situations, the best thing to do is to save the error report into a log file and use it later on to debug your code.

Lets see how we can separate the “type” from the rest of the message whenever we encounter an error.

Now let’s look at some examples to help us understand better how these things work shall we?

Example#1

As explained in the short section, to print the type of an exception you simply catch the exception itself and store it in a variable using the try-catch feature. And then you print the type of it using the inbuilt function type()

Let’s say you have a dictionary containing your favorite animals and their average lifespans:

animals = {
    "Lion" : 15,
    "Horse" : 30,
    "Elephant": 60,
    "Sea turtle": 75,
}

Now if you tried to access the lifespan of ‘Horse’:

print(animals["Horse"])

We get his age:

30

Let me get the lifespan of a blue whale now, remember, we didn’t include ‘Blue Whale’ in our dictionary:

print(animal["Blue Whale"])

Now python has no clue what to do, it is the same “water in gas tank” situation!

This stops the script from executing and we are left with the following error message

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    print(animal["Blue Whale"])
KeyError: 'Blue Whale'


If you don’t want to log this whole complex message and just want to log what type of exception it is, here’s how you can do that.

# enclose the code that caused the error in the try block:
try:
  print(animal["Blue Whale"])

# catch the error and store it as a variable:
except Exception as e:
  print(type(e))

And now the output is:

<class 'KeyError'>

We see that the error we need to deal with is a KeyError, and we know that this is when you try to invoke or access a key that doesn’t exist in your dictionary.

type() prints the class name of whatever objects you pass in.

Knowing that, now you can either

  • add the missing key, and its respective value or
  • make some workaround and add a default value whenever you are dealing with this issue as explained in detail in our other article 3 ways to Handle KeyErrors in Python

Advanced: Understanding the Exception class

In the last example we saw that when catching the error in the except part, we only used the “Exception” class instead of specifically saying what the “type” of exception it is(in this case a KeyError).

And yet the interpreter was able to catch it without any issues! How so?

The explanation for this is pretty simple and straightforward. The Exception class is a class from which all the in-built exceptions are derived from. It serves as a base class for all the exceptions raised by the Python interpreter.

So when we just specify the Exception class, the interpreter checks if the current error is a child class of the Exception class or not. It always is, so it catches the exception!

I hope that make sense, if not then you need to learn the concept of inheritance and how it works.

For now just remember that all exception types belong the “Exception” family, just like Lions, Horses, Sea Turtles and Elephants belong to the “Animal” family!

Wouldn’t it be cleaner if we can just print “KeyError” instead of <class ‘KeyError’>?

Lets take one more example and see how we can do that!

Example 2, printing just the exception name without the “<class>” part

Hi, my name is Jamal and I’m 20. 

I want to print that sentence in Python, let me try:

name = "Jamal"
age = 20
print("Hi, my name is " + name + " and I’m " + age)

Oh no, I’ve seem to come across an error:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print("Hi, my name is " + name + " and I’m " + age)
TypeError: can only concatenate str (not "int") to str

The error seems to be that I cannot add an int type variable to an str type variable. I should’ve converted the variable age to a string before I concatenated them together. We can also see that it is a TypeError.

We’ve already learned how we can print the error type as:

<class 'TypeError'>

Let’s go a step further and print just

TypeError

As usual, use a try-except block, with an extra step, take some time and look at the example below carefully and try to figure out what that extra step is!

try:
  name = "Jamal"
  age = 20
  print("Hi, my name is " + name + " and I’m " + age)
except Exception as e:
  print(e.__class__.__name__)

What this does is it gets the e exception object’s class (e.__class__) and from which it gets us this class’s name (e.__class__.__name__).

I get the error message just like I wanted!:

TypeError

Pretty easy right?

The type() function internally also uses the same metadata, but it just formats it out with the <class> header as shown in example-1.

So you got the exception type, now what?

If you are not sure how to proceed, you can follow the steps below instead.

  1. Google the exception name to understand what it is. If you can learn about it and understand the issue properly, you can debug it easily
  2. Go back to the code in the try block and read it carefully one-line-at-a-time and try to understand the issue calmly and slowly.
  3. Now, try to replicate the error and then apply the fix
  4. Finally, test the fix under different conditions to ensure that the bug is properly dealt with in all scenarios

Remember debugging is always a part of coding!

Now give it to your client once more and pray that exception never comes up again!

What other details are contained in an exception?

There are 3 main details contained in an exception message.

  • Exception Type (which we have just learned)
  • Exception Message and
  • Stacktrace

You can see those 3 parts in the picture below.

These 3 details are packed together into an object of type “Traceback“, which is aptly named as these 3 details can help us trace back to the point of the error.

We have written another article explaining each of these parts and what is each of their role in debugging the problem. You can find that article in the link below.

Python: Details contained in an Exception

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

And on that note, I will end this article!

Congratulations on making it to the end, not many people have the perseverance to finish what they start!

I hope you learned something and got some value out of this article.

And as usual, you’re always welcome to return to the Embedded Inventor for more articles!

Here are some more articles that might interest you.

Related articles

Python: Details contained in an Exception

Print just the message of an exception

Python: Print StackTrace on Exception!

Python: Catch Exception and Print

Python Dicts: Most Common Exceptions and How to Avoid Them!

Thanks to Mohammad Jamal for his contributions to the creation of 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