Print just the message of an exception

In this article let’s learn how to print just the message of an exception/error message.

Whenever a Python program crashes with an exception we get a crazy long text trying to tell us what went wrong. In this article, we’ll explore how to print just the most useful part of that text, i.e. the “Exception Message”.

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

Print just the Exception Message: The Recipe

Let’s start with a quick example.

    x = 1/0 #Divide by zero
except Exception as e:

On running this code you will get the following output


division by zero

As you can see instead of a huge text, we get a simple one-liner explaining what the problem is.

The following steps are used to print just the message of the error text

Step#1: Use a try-catch block and store the caught exception in an exception object, like this:

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

Step#2: Simply give the exception object “e” to the in-built print() function!

    # some code that might raise an exception
except Exception as e:

If the above explanation raises more questions than answers, don’t worry as this was meant to be a quick refresher for those who are already familiar with the topic.

The rest of the article is written keeping beginners in mind, so I suggest you get yourself a nice and quiet place, sit down for 5 minutes and scroll through!

The following questions will be answered throughout this article

  • how to print a custom message instead of what comes with the exception object “e”
  • how to use the exception message to solve bugs
  • In what situations this recipe can be useful

along with various interesting information about the exception class!

Printing Exception Message, a detailed look

Let’s face it, we all encounter errors no matter how hard we try to avoid them. It really can’t be avoided, coding and errors go hand in hand, unfortunately, but you know what else goes hand in hand with coding? Debugging! Rectifying your code and making them get back up and running is just another day for developers like us.

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 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 refreshed our memories on what exceptions are and how to print them, let us next try and answer the question: Why do we need the message of an Exception?

Understanding why we need to know the “message” 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 a way to work with that.

There are several types of exceptions, each with its own unique message for unique scenarios.

For example, as we saw earlier,

  • if you divide a number by zero you’ll be getting the message “division by zero” in your screens to indicate your program exited due to a ZeroDivisionError
  • If you try to invoke or access a key that doesn’t exist in your dictionary, you’ll be getting the message “KeyError <keyname>” to indicate that your program exited due to a KeyError.

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

How to deal with error messages?

When we face the error messages themselves, we need to figure out what it means. For example, consider the 1-line code below.


Running the line above will give the following output.


File "", line 1, in <module>
ZeroDivisionError: division by zero

Since I divided a number by 0 in the program, an exception was raised. This message, albeit extremely informative, can be long and difficult to understand. Imagine in scenarios where the exception happened inside a function, which is inside another one, and so on, it will be a long traceback message indeed!

Did you know it is possible to print parts of the exception message separately instead of the whole message? And that’s exactly what we’ll be talking about today, we’ll be looking into how to print just the exception message i.e the last part of the last line (Here is an article on how to print just the exception type)

Keen readers will come up with the following question next!

What more details are contained in an exception?

There are 3 main details contained in an exception.

  • Exception Message (which we are about to learn)
  • Exception Type and
  • Stack-trace

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!

Now that we have covered the fundamentals, let us see some examples of how to print the message of an exception

Printing the default message

One way to print the message is by catching the exception using a try-except block and storing it as an exception object, and then simply print it.

This method is pretty simple and short, have a look.

except Exception as e:


division by zero

The exception name here is ZeroDivisionError, this happens if we divide a number by 0. The exception message for this exception is what we got in our output.


How print() gave us this message?

Whenever we pass any object in python to the in-built print function, the python interpreter calls the __repr__() method of the object in the background, which returns a string representation of the object.

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 ZeroDivisionError).

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 makes 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 to the “Exception” family, just like Lions, Horses, Sea Turtles and Elephants belong to the “Animal” family!

Let’s try this again with another example

colors = {"red":0, "black":1, "blue":2, "white":3, "yellow":4}

except Exception as e:


name 'color' is not defined

What happened was, since I tried to access a dictionary object that doesn’t exist (the defined dictionary in the program is named colors whereas I called for a dictionary called color), a NameError exception was raised. And since we printed only the exception’s message, we got NameError’s respective message just like we wanted, the name ‘color’ is not defined

Printing Custom messages

The code for this getting custom messages is even simpler than the last one!

except ZeroDivisionError:
  print("Dividing by zero is undefined in mathematics")


Dividing by zero is undefined in mathematics

Here we just caught the exception and printed out our own custom message. While the message is more user-friendly, the main problem with this approach is we cannot use it to solve the bug by quick googling.

And with that example, I will end this article.

Congratulations on reaching here! Not many people are equipped with this amount of perseverance and focus. I hope you learned something useful and got some value out of this article!

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

Here are some more articles that might interest you.

Related articles

Python: Catch Exception and Print

Python: Print StackTrace on Exception!

Python: Print Exception Type

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

Thanks to Namazi Jamal for his contributions in writing this article!

Photo of author
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