âšď¸ Skipped - page is already crawled
| Filter | Status | Condition | Details |
|---|---|---|---|
| HTTP status | PASS | download_http_code = 200 | HTTP 200 |
| Age cutoff | PASS | download_stamp > now() - 6 MONTH | 2 months ago |
| History drop | PASS | isNull(history_drop_reason) | No drop reason |
| Spam/ban | PASS | fh_dont_index != 1 AND ml_spam_score = 0 | ml_spam_score=0 |
| Canonical | PASS | meta_canonical IS NULL OR = '' OR = src_unparsed | Not set |
| Property | Value |
|---|---|
| URL | https://embeddedinventor.com/print-just-the-message-of-an-exception/ |
| Last Crawled | 2026-02-09 13:26:45 (1 month ago) |
| First Indexed | 2023-01-17 02:45:34 (3 years ago) |
| HTTP Status Code | 200 |
| Meta Title | Print just the message of an exception |
| Meta Description | null |
| Meta Canonical | null |
| Boilerpipe Text | 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.
Letâs start with a quick example.
try:
x = 1/0 #Divide by zero
except Exception as e:
print(e)
On running this code you will get the following output
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:
try:
# 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!
try:
# some code that might raise an exception
except Exception as e:
print(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.
print(20/0)
Running the line above will give the following output.
OUTPUT
File "main.py", line 1, in <module>
print(20/0)
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.
try:
print(1/0)
except Exception as e:
print(e)
OUTPUT:
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.
Advanced:
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}
try:
print(color["red"])
except Exception as e:
print(e)
OUTPUT:
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!
try:
print(1/0)
except ZeroDivisionError:
print("Dividing by zero is undefined in mathematics")
OUTPUT:
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! |
| Markdown | [Skip to content](https://embeddedinventor.com/print-just-the-message-of-an-exception/#content "Skip to content")
[](https://embeddedinventor.com/)
[](https://embeddedinventor.com/ "Embedded Inventor")
Menu
- [Home](http://embeddedinventor.com/)
- [Python](https://embeddedinventor.com/category/python/)
- [Linux](https://embeddedinventor.com/category/linux/)
- [Embedded Systems](https://embeddedinventor.com/category/embedded-systems/)
- [Videos](https://embeddedinventor.com/category/miscellaneous/videos/)
- [About Us](https://embeddedinventor.com/about/)
Menu
- [Home](http://embeddedinventor.com/)
- [Python](https://embeddedinventor.com/category/python/)
- [Linux](https://embeddedinventor.com/category/linux/)
- [Embedded Systems](https://embeddedinventor.com/category/embedded-systems/)
- [Videos](https://embeddedinventor.com/category/miscellaneous/videos/)
- [About Us](https://embeddedinventor.com/about/)


# Print just the message of an exception
September 27, 2023
January 15, 2023
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.
```
try:
x = 1/0 #Divide by zero
except Exception as e:
print(e)
```
On running this code you will get the following output
**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:
```
try:
# 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\!
```
try:
# some code that might raise an exception
except Exception as e:
print(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\!](https://embeddedinventor.com/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.
```
print(20/0)
```
Running the line above will give the following output.
**OUTPUT**
```
File "main.py", line 1, in <module>
print(20/0)
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](https://embeddedinventor.com/python-printing-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](https://embeddedinventor.com/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.
```
try:
print(1/0)
except Exception as e:
print(e)
```
OUTPUT:
```
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.
**Advanced:**
**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}
try:
print(color["red"])
except Exception as e:
print(e)
```
**OUTPUT:**
```
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\!
```
try:
print(1/0)
except ZeroDivisionError:
print("Dividing by zero is undefined in mathematics")
```
**OUTPUT:**
```
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](https://embeddedinventor.com/python-catch-exception-and-print-2/)
[Python: Print StackTrace on Exception\!](https://embeddedinventor.com/python-print-stacktrace-on-exception/)
[Python: Print Exception Type](https://embeddedinventor.com/python-printing-exception-type/)
[Python Dicts: Most Common Exceptions and How to Avoid Them\!](https://embeddedinventor.com/python-dicts-most-common-exceptions-and-how-to-avoid-them/)
Thanks to Namazi Jamal for his contributions in writing this article\!


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](https://www.linkedin.com/in/balaji-gunasekaran-90754a136/)
## Categories
## Categories
## About Author
[](https://embeddedinventor.com/author/balaji200988/)
### [Balaji Gunasekaran](https://embeddedinventor.com/author/balaji200988/)
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](https://www.linkedin.com/in/balaji-gunasekaran-90754a136/)
- [Privacy Policy](https://embeddedinventor.com/privacy-policy/)
- [Refund Policy](https://embeddedinventor.com/?page_id=7421)
- [Terms and Conditions](https://embeddedinventor.com/terms-and-conditions/)
- [About EmbeddedInventor.com](https://embeddedinventor.com/about/)
- [Get in Touch](https://embeddedinventor.com/get-in-touch/)
Š 2026 embeddedinventor.com
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking âAcceptâ, you consent to the use of ALL the cookies.
[Do not sell my personal information]().
[settings]()[OKAY]()
Privacy & Cookies Policy
Close
#### Privacy Overview
This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are as essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
[Necessary]()
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
[SAVE & ACCEPT]() |
| Readable Markdown | 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.
Letâs start with a quick example.
```
try:
x = 1/0 #Divide by zero
except Exception as e:
print(e)
```
On running this code you will get the following output
**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:
```
try:
# 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\!
```
try:
# some code that might raise an exception
except Exception as e:
print(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\!](https://embeddedinventor.com/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.
```
print(20/0)
```
Running the line above will give the following output.
**OUTPUT**
```
File "main.py", line 1, in <module>
print(20/0)
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](https://embeddedinventor.com/python-printing-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](https://embeddedinventor.com/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.
```
try:
print(1/0)
except Exception as e:
print(e)
```
OUTPUT:
```
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.
**Advanced:**
**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}
try:
print(color["red"])
except Exception as e:
print(e)
```
**OUTPUT:**
```
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\!
```
try:
print(1/0)
except ZeroDivisionError:
print("Dividing by zero is undefined in mathematics")
```
**OUTPUT:**
```
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](https://embeddedinventor.com/python-catch-exception-and-print-2/)
[Python: Print StackTrace on Exception\!](https://embeddedinventor.com/python-print-stacktrace-on-exception/)
[Python: Print Exception Type](https://embeddedinventor.com/python-printing-exception-type/)
[Python Dicts: Most Common Exceptions and How to Avoid Them\!](https://embeddedinventor.com/python-dicts-most-common-exceptions-and-how-to-avoid-them/)
Thanks to Namazi Jamal for his contributions in writing this article\! |
| Shard | 81 (laksa) |
| Root Hash | 14039567429692063881 |
| Unparsed URL | com,embeddedinventor!/print-just-the-message-of-an-exception/ s443 |