🕷️ Crawler Inspector

URL Lookup

Direct Parameter Lookup

Raw Queries and Responses

1. Shard Calculation

Query:
Response:
Calculated Shard: 81 (from laksa114)

2. Crawled Status Check

Query:
Response:

3. Robots.txt Check

Query:
Response:

4. Spam/Ban Check

Query:
Response:

5. Seen Status Check

ℹ️ Skipped - page is already crawled

📄
INDEXABLE
✅
CRAWLED
1 month ago
🤖
ROBOTS ALLOWED

Page Info Filters

FilterStatusConditionDetails
HTTP statusPASSdownload_http_code = 200HTTP 200
Age cutoffPASSdownload_stamp > now() - 6 MONTH2 months ago
History dropPASSisNull(history_drop_reason)No drop reason
Spam/banPASSfh_dont_index != 1 AND ml_spam_score = 0ml_spam_score=0
CanonicalPASSmeta_canonical IS NULL OR = '' OR = src_unparsedNot set

Page Details

PropertyValue
URLhttps://embeddedinventor.com/print-just-the-message-of-an-exception/
Last Crawled2026-02-09 13:26:45 (1 month ago)
First Indexed2023-01-17 02:45:34 (3 years ago)
HTTP Status Code200
Meta TitlePrint just the message of an exception
Meta Descriptionnull
Meta Canonicalnull
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") [![Embedded Inventor](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20300%20300'%3E%3C/svg%3E)![Embedded Inventor](https://embeddedinventor.com/wp-content/uploads/2023/02/logo_350px-300x300-1.png.webp)](https://embeddedinventor.com/) [![Embedded Inventor](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20300%20300'%3E%3C/svg%3E)![Embedded Inventor](https://embeddedinventor.com/wp-content/uploads/2023/02/logo_350px-300x300-1.png.webp)](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/) ![](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20960%20540'%3E%3C/svg%3E) ![](https://embeddedinventor.com/wp-content/uploads/2023/01/Title-images-1.jpg.webp) # 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. ![](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20330%20438'%3E%3C/svg%3E) ![](https://embeddedinventor.com/wp-content/uploads/2023/01/petrol-station-296676_1280-2-771x1024.png.webp) 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. ![](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%201024%20452'%3E%3C/svg%3E) ![](https://embeddedinventor.com/wp-content/uploads/2023/02/DetailsException-4-1024x452.png.webp) 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\! ![Photo of author](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20120%20120'%3E%3C/svg%3E) ![Photo of author](https://embeddedinventor.com/wp-content/uploads/2021/04/1618956914240-150x150.jpg.webp) 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 [![](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%2064%2064'%3E%3C/svg%3E)![](https://embeddedinventor.com/wp-content/uploads/2021/04/1618956914240-96x96.jpg.webp)](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. ![](https://embeddedinventor.com/wp-content/uploads/2023/01/petrol-station-296676_1280-2-771x1024.png.webp) 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. ![](https://embeddedinventor.com/wp-content/uploads/2023/02/DetailsException-4-1024x452.png.webp) 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\!
Shard81 (laksa)
Root Hash14039567429692063881
Unparsed URLcom,embeddedinventor!/print-just-the-message-of-an-exception/ s443