ℹ️ 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/python-exception-tutorial-printing-error-messages/ |
| Last Crawled | 2026-02-12 23:26:38 (1 month ago) |
| First Indexed | 2021-03-24 22:32:40 (5 years ago) |
| HTTP Status Code | 200 |
| Meta Title | Python: Printing Exception (Error Message) |
| Meta Description | null |
| Meta Canonical | null |
| Boilerpipe Text | In this article, let us learn about printing error messages from Exceptions with the help of 5 specifically chosen examples.
I have divided this article into 2 major sections
Printing
custom error messages
and
Printing
a specific part of the default error message
. By “
default error message
“, I mean the error message that you typically get in the command line if you did not catch a given exception)
Depending on which of the 2 options above you are looking for, you can jump to the respective section of the article using the table of content below.
So, let’s begin!
The Fundamentals
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
If you feel that your basics could use some boosting, I suggest reading the following article
Exceptions in Python: Everything You Need To Know!
Now that we have covered the basics, lets get back to the topic and learn how to print custom messages!
Printing Error messages: The Video
If you are a visual learner, I invite you to watch the following video we made on the topic of printing exceptions!
You can only cover so much in a video. Read on for a more thorough explanation on printing error messages
Printing Error messages: A Thorough Explanation!
There are 3 ways to print custom error messages in Python. Let us start with the simplest of the 3, which is using a
print()
statement.
Option#1: Using a simple
print()
statement
The first and easiest option is to print error messages using a simple
print()
statement as shown in the example below.
try:
#Some Problematic code that can produce Exceptions
x = 5/0
except Exception as e:
print('A problem has occurred from the Problematic code: ', e)
Running this code will give the output below.
A problem has occurred from the Problematic code: division by zero
Here the line “
x = 5/0″
in Example 1 above raised a “
ZeroDivisionError
” which was caught by our
except
clause and the
print()
statement printed the default error message which is “
division by zero”
to the standard output.
One thing to note here is the line “
except Exception as e
“. This line of code’s function is to catch all possible exceptions, whichever occurs first as an “
Exception
” object. This object is stored in the variable “
e
” (line 4), which returns the string ‘
division by zero
‘ when used with the
print()
statement (line 5).
To summarize
if you wish to print out the default error message along with a custom message use Option#1.
This is the simplest way to print error messages in python. But this option of putting your custom messages into print statements
might not work in cases where you might be handling a list of exceptions using a single
except
clause
. If you are not exactly sure how to catch a list of exceptions using a single
except
clause, I suggest reading my other article in the link below.
Python: 3 Ways to Catch Multiple Exceptions in a single “except” clause
There I have explained the 3 ways through which you can catch a list of exceptions along with tips on when is the right situation to catch each of these exceptions.
Now that we have learned how to print the default string which comes with an exception object, let us next learn
how to customize the message that
e
carried
(the string ‘
division by zero
‘) and replace that with our own custom error message.
Option#2: Using Custom Exception classes to get customized error messages
In Python, you can define your own custom exception classes by inheriting from another Exception class as shown in the code below.
class MyOwnException(Exception):
def __str__(self):
return 'My Own Exception has occurred'
def __repr__(self):
return str(type(self))
try:
raise MyOwnException
except MyOwnException as e:
print(e)
print(repr(e))
How to choose the exception class to inherit from?
In the above example, I have inherited from the
Exception
class in python, but the recommended practice is to choose a class that closely resembles your use-case.
For example, say you are trying to work with a
string
type object and you are given a
list
type object instead, here you should inherit your custom exception from
TypeError
since this Exception type closely resembles your use case which is “the variable is not of expected type”.
If you are looking for getting an appropriate Exception class to inherit from, I recommend having a look at all the built-in exceptions from the official python page
here
. For the sake of keeping this example simple, I have chosen the higher-level exception type named “
Exception
” class to inherit from.
In the code below, we are collecting values from the user and to tell the user that there is an error in the value entered we are using the
ValueError
class.
class EnteredGarbageError(ValueError):
def __str__(self):
return 'You did not select an option provided!'
try:
options = ['A', 'B', 'C']
x = input('Type A or B or C: ')
if x not in options:
raise EnteredGarbageError
else:
print ('You have chosen: ', x)
except EnteredGarbageError as err:
print(err)
Now that we understand how to choose a class to inherit from, let us next have a look at how to customize the default error messages that these classes return.
How to customize the error message in our custom exception class?
To help us achieve our purpose here which is to print some custom error messages, all objects in python come with 2 methods named
__str__
and
__repr__
. This is pronounced “dunder-str” and “dunder-repr” where “dunder” is short for “double underscore”.
Dunder-str method
:
The method __str__ returns a string and this is what the built-in
print()
function calls whenever we pass it an object to print.
print(object1)
In the line above, python will call the
__str__
method of the object and prints out the string returned by that method.
Let us have a look at what python’s official documentation over at
python.org
has to say about the
str
method.
https://docs.python.org/3/reference/datamodel.html#object.
str
In simpler words,
the str method returns a human-readable string for logging purposes,
and when this information is passed to the built-in function
print()
, the string it returns gets printed.
So since our implementation of
str
returns the string “
My Own Exception has occurred
” this string got printed on the first line of the exception message.
Dunder-repr method
:
__repr__
is another method available in all objects in python.
Where it differs from the dunder-str method is the fact that while
the
__str__
is used for getting a “friendly message”, the
__repr__
method is used for getting, a more of a, “formal message”.
You can think of str as a text you got from your friends and repr as a notice you got from a legal
repr
esentative!
The below screenshot from
python’s official documentation
explains the use of
__repr__
method.
https://docs.python.org/3/reference/datamodel.html#object.
repr
Again, in simpler words,
repr
is typically used to print some “formal” or “official” information about an object in Python
In our Example 2 above, the
repr
method returned the class name using the built-in
type()
function.
Next, let us see another variation where we can print different error messages using a single Exception class without making a custom class.
Option#3: Custom Error messages from the raise statement
try:
raise Exception('I wish to print this message')
except Exception as error:
print(error)
Lucky for us, python has made this process incredibly simple! Just pass in the message as an argument to the type of exception you wish to raise and this will print that custom message instead!
In the above code, we are throwing an exception of type “Exception” by calling its constructor and giving the custom message as an argument, which then overrides the default
__str__
method to return the string passed in.
If you wish to learn more about raise statement, I suggest reading my other article in the link below
Python: Manually throw/raise an Exception using the “raise” statement
where I have explained 3 ways you can use the
raise
statement in python and when to use each.
But when to use option 2 and when to use option 3?
On the surface, Option#3 of passing in the custom message may look like it made option#2 of using custom classes useless. But the main reason to use Option#2 is the fact that
Option#2 can be used to override more than just the
__str__
method
.
Let’s next move on to section 2 of this article and look at how to choose a specific part of the default error message (the error printed on the console when you don’t catch an exception) and use that to make our own error messages
Choosing Parts of Default Error Messages to print
To understand what I mean by “Default Error Message” let us see an example
raise ValueError("This is an ValueError")
This line when run, will print the following error message
Traceback (most recent call last):
File "<ipython-input-24-57127e33a735>", line 1, in <module>
raise ValueError("This is an ValueError")
ValueError: This is an ValueError
This error message contains 3 Parts
Exception Type (ValueError)
Error message (This is an ValueError)
and the stack trace (the 1st few lines showing us where exactly in the program the exception has occurred)
For visual learners out there we have also made an interesting video on that topic!
The information needed
to extract and use each of the individual pieces of information listed above and
when to use what piece of information
is already covered with the help of several examples in my previous article in the link below
Python Exceptions: Getting and Handling Error Messages as strings.
And with that I will end this article!
If you are looking for another interesting read, try the article in the link below.
Exceptions in Python: Everything You Need To Know!
The above article covers all the basics of Exception handling in Python like
when and how to ignore exceptions
when and how to retry the problematic code that produced the exception and
when and how to log the errors
I hope you enjoyed reading this article and got some value from it.
Feel free to share it with your friends and colleagues! |
| Markdown | [Skip to content](https://embeddedinventor.com/python-exception-tutorial-printing-error-messages/#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/)


# Python: Printing Exception (Error Message)
September 27, 2023
March 22, 2021
In this article, let us learn about printing error messages from Exceptions with the help of 5 specifically chosen examples.
I have divided this article into 2 major sections
1. Printing **custom error messages** and
2. Printing **a specific part of the default error message**. By “*default error message*“, I mean the error message that you typically get in the command line if you did not catch a given exception)
Depending on which of the 2 options above you are looking for, you can jump to the respective section of the article using the table of content below.
**Contents**
[1 The Fundamentals](https://embeddedinventor.com/python-exception-tutorial-printing-error-messages/#The_Fundamentals)
[1\.1 Exceptions, What are they?](https://embeddedinventor.com/python-exception-tutorial-printing-error-messages/#Exceptions_What_are_they)
[2 Printing Error messages: The Video](https://embeddedinventor.com/python-exception-tutorial-printing-error-messages/#Printing_Error_messages_The_Video)
[3 Printing Error messages: A Thorough Explanation\!](https://embeddedinventor.com/python-exception-tutorial-printing-error-messages/#Printing_Error_messages_A_Thorough_Explanation)
[3\.1 Option\#1: Using a simple print() statement](https://embeddedinventor.com/python-exception-tutorial-printing-error-messages/#Option1_Using_a_simple_print_statement)
[3\.2 Option\#2: Using Custom Exception classes to get customized error messages](https://embeddedinventor.com/python-exception-tutorial-printing-error-messages/#Option2_Using_Custom_Exception_classes_to_get_customized_error_messages)
[3\.3 Option\#3: Custom Error messages from the raise statement](https://embeddedinventor.com/python-exception-tutorial-printing-error-messages/#Option3_Custom_Error_messages_from_the_raise_statement)
[4 Choosing Parts of Default Error Messages to print](https://embeddedinventor.com/python-exception-tutorial-printing-error-messages/#Choosing_Parts_of_Default_Error_Messages_to_print)
So, let’s begin\!
## The Fundamentals
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
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/)
Now that we have covered the basics, lets get back to the topic and learn how to print custom messages\!
## Printing Error messages: The Video
If you are a visual learner, I invite you to watch the following video we made on the topic of printing exceptions\!
You can only cover so much in a video. Read on for a more thorough explanation on printing error messages
## Printing Error messages: A Thorough Explanation\!
There are 3 ways to print custom error messages in Python. Let us start with the simplest of the 3, which is using a *print()* statement.
### Option\#1: Using a simple *print()* statement
The first and easiest option is to print error messages using a simple *print()* statement as shown in the example below.
```
try:
#Some Problematic code that can produce Exceptions
x = 5/0
except Exception as e:
print('A problem has occurred from the Problematic code: ', e)
```
Running this code will give the output below.
```
A problem has occurred from the Problematic code: division by zero
```
Here the line “*x = 5/0″* in Example 1 above raised a “*ZeroDivisionError*” which was caught by our *except* clause and the *print()* statement printed the default error message which is “*division by zero”* to the standard output.
One thing to note here is the line “*except Exception as e*“. This line of code’s function is to catch all possible exceptions, whichever occurs first as an “*Exception*” object. This object is stored in the variable “*e*” (line 4), which returns the string ‘*division by zero*‘ when used with the *print()* statement (line 5).
To summarize **if you wish to print out the default error message along with a custom message use Option\#1.**
This is the simplest way to print error messages in python. But this option of putting your custom messages into print statements **might not work in cases where you might be handling a list of exceptions using a single *except* clause**. If you are not exactly sure how to catch a list of exceptions using a single *except* clause, I suggest reading my other article in the link below.
[Python: 3 Ways to Catch Multiple Exceptions in a single “except” clause](https://embeddedinventor.com/python-3-ways-to-catch-multiple-exceptions-in-a-single-except-clause/)
There I have explained the 3 ways through which you can catch a list of exceptions along with tips on when is the right situation to catch each of these exceptions.
Now that we have learned how to print the default string which comes with an exception object, let us next learn **how to customize the message that *e* carried** (the string ‘*division by zero*‘) and replace that with our own custom error message.
### Option\#2: Using Custom Exception classes to get customized error messages
In Python, you can define your own custom exception classes by inheriting from another Exception class as shown in the code below.
```
class MyOwnException(Exception):
def __str__(self):
return 'My Own Exception has occurred'
def __repr__(self):
return str(type(self))
try:
raise MyOwnException
except MyOwnException as e:
print(e)
print(repr(e))
```
#### **How to choose the exception class to inherit from?**
In the above example, I have inherited from the *Exception* class in python, but the recommended practice is to choose a class that closely resembles your use-case.
For example, say you are trying to work with a *string* type object and you are given a *list* type object instead, here you should inherit your custom exception from *TypeError* since this Exception type closely resembles your use case which is “the variable is not of expected type”.
If you are looking for getting an appropriate Exception class to inherit from, I recommend having a look at all the built-in exceptions from the official python page [here](https://docs.python.org/3/library/exceptions.html#bltin-exceptions). For the sake of keeping this example simple, I have chosen the higher-level exception type named “*Exception*” class to inherit from.
In the code below, we are collecting values from the user and to tell the user that there is an error in the value entered we are using the *ValueError* class.
```
class EnteredGarbageError(ValueError):
def __str__(self):
return 'You did not select an option provided!'
try:
options = ['A', 'B', 'C']
x = input('Type A or B or C: ')
if x not in options:
raise EnteredGarbageError
else:
print ('You have chosen: ', x)
except EnteredGarbageError as err:
print(err)
```
Now that we understand how to choose a class to inherit from, let us next have a look at how to customize the default error messages that these classes return.
#### **How to customize the error message in our custom exception class?**
To help us achieve our purpose here which is to print some custom error messages, all objects in python come with 2 methods named *\_\_str\_\_* and *\_\_repr\_\_*. This is pronounced “dunder-str” and “dunder-repr” where “dunder” is short for “double underscore”.
**Dunder-str method**:
The method \_\_str\_\_ returns a string and this is what the built-in *print()* function calls whenever we pass it an object to print.
```
print(object1)
```
In the line above, python will call the *\_\_str\_\_* method of the object and prints out the string returned by that method.
Let us have a look at what python’s official documentation over at [python.org](http://docs.python.org/ "Python Exception Tutorial: Printing Error Messages (5 Examples!)") has to say about the **str** method.


https://docs.python.org/3/reference/datamodel.html\#object.**str**
In simpler words, **the str method returns a human-readable string for logging purposes,** **and when this information is passed to the built-in function *print()*, the string it returns gets printed.**
So since our implementation of **str** returns the string “*My Own Exception has occurred*” this string got printed on the first line of the exception message.
**Dunder-repr method**:
*\_\_repr\_\_* is another method available in all objects in python.
Where it differs from the dunder-str method is the fact that while **the *\_\_str\_\_* is used for getting a “friendly message”, the *\_\_repr\_\_* method is used for getting, a more of a, “formal message”.** You can think of str as a text you got from your friends and repr as a notice you got from a legal **repr**esentative\!
The below screenshot from [python’s official documentation](https://docs.python.org/3/reference/datamodel.html#object.repr) explains the use of *\_\_repr\_\_* method.


https://docs.python.org/3/reference/datamodel.html\#object.**repr**
Again, in simpler words, **repr** is typically used to print some “formal” or “official” information about an object in Python
In our Example 2 above, the **repr** method returned the class name using the built-in *type()* function.
Next, let us see another variation where we can print different error messages using a single Exception class without making a custom class.
### Option\#3: Custom Error messages from the raise statement
```
try:
raise Exception('I wish to print this message')
except Exception as error:
print(error)
```
Lucky for us, python has made this process incredibly simple! Just pass in the message as an argument to the type of exception you wish to raise and this will print that custom message instead\!
In the above code, we are throwing an exception of type “Exception” by calling its constructor and giving the custom message as an argument, which then overrides the default *\_\_str\_\_* method to return the string passed in.
If you wish to learn more about raise statement, I suggest reading my other article in the link below
[Python: Manually throw/raise an Exception using the “raise” statement](https://embeddedinventor.com/python-manually-throw-raise-an-exception-using-the-raise-statement/)
where I have explained 3 ways you can use the *raise* statement in python and when to use each.
**But when to use option 2 and when to use option 3?**
On the surface, Option\#3 of passing in the custom message may look like it made option\#2 of using custom classes useless. But the main reason to use Option\#2 is the fact that **Option\#2 can be used to override more than just the *\_\_str\_\_* method**.
Let’s next move on to section 2 of this article and look at how to choose a specific part of the default error message (the error printed on the console when you don’t catch an exception) and use that to make our own error messages
## Choosing Parts of Default Error Messages to print
To understand what I mean by “Default Error Message” let us see an example
```
raise ValueError("This is an ValueError")
```
This line when run, will print the following error message
```
Traceback (most recent call last):
File "<ipython-input-24-57127e33a735>", line 1, in <module>
raise ValueError("This is an ValueError")
ValueError: This is an ValueError
```
This error message contains 3 Parts
- Exception Type (ValueError)
- Error message (This is an ValueError)
- and the stack trace (the 1st few lines showing us where exactly in the program the exception has occurred)
For visual learners out there we have also made an interesting video on that topic\!
The information needed
- to extract and use each of the individual pieces of information listed above and
- when to use what piece of information
is already covered with the help of several examples in my previous article in the link below
[Python Exceptions: Getting and Handling Error Messages as strings.](https://embeddedinventor.com/python-exceptions-getting-and-handling-error-messages-as-strings/)
And with that I will end this article\!
If you are looking for another interesting read, try the article in the link below.
[Exceptions in Python: Everything You Need To Know\!](https://embeddedinventor.com/exceptions-in-python-everything-you-need-to-know/)
The above article covers all the basics of Exception handling in Python like
- when and how to ignore exceptions
- when and how to retry the problematic code that produced the exception and
- when and how to log the errors
I hope you enjoyed reading this article and got some value from it.
Feel free to share it with your friends and colleagues\!


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 us learn about printing error messages from Exceptions with the help of 5 specifically chosen examples.
I have divided this article into 2 major sections
1. Printing **custom error messages** and
2. Printing **a specific part of the default error message**. By “*default error message*“, I mean the error message that you typically get in the command line if you did not catch a given exception)
Depending on which of the 2 options above you are looking for, you can jump to the respective section of the article using the table of content below.
So, let’s begin\!
## The Fundamentals
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
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/)
Now that we have covered the basics, lets get back to the topic and learn how to print custom messages\!
## Printing Error messages: The Video
If you are a visual learner, I invite you to watch the following video we made on the topic of printing exceptions\!
You can only cover so much in a video. Read on for a more thorough explanation on printing error messages
## Printing Error messages: A Thorough Explanation\!
There are 3 ways to print custom error messages in Python. Let us start with the simplest of the 3, which is using a *print()* statement.
### Option\#1: Using a simple *print()* statement
The first and easiest option is to print error messages using a simple *print()* statement as shown in the example below.
```
try:
#Some Problematic code that can produce Exceptions
x = 5/0
except Exception as e:
print('A problem has occurred from the Problematic code: ', e)
```
Running this code will give the output below.
```
A problem has occurred from the Problematic code: division by zero
```
Here the line “*x = 5/0″* in Example 1 above raised a “*ZeroDivisionError*” which was caught by our *except* clause and the *print()* statement printed the default error message which is “*division by zero”* to the standard output.
One thing to note here is the line “*except Exception as e*“. This line of code’s function is to catch all possible exceptions, whichever occurs first as an “*Exception*” object. This object is stored in the variable “*e*” (line 4), which returns the string ‘*division by zero*‘ when used with the *print()* statement (line 5).
To summarize **if you wish to print out the default error message along with a custom message use Option\#1.**
This is the simplest way to print error messages in python. But this option of putting your custom messages into print statements **might not work in cases where you might be handling a list of exceptions using a single *except* clause**. If you are not exactly sure how to catch a list of exceptions using a single *except* clause, I suggest reading my other article in the link below.
[Python: 3 Ways to Catch Multiple Exceptions in a single “except” clause](https://embeddedinventor.com/python-3-ways-to-catch-multiple-exceptions-in-a-single-except-clause/)
There I have explained the 3 ways through which you can catch a list of exceptions along with tips on when is the right situation to catch each of these exceptions.
Now that we have learned how to print the default string which comes with an exception object, let us next learn **how to customize the message that *e* carried** (the string ‘*division by zero*‘) and replace that with our own custom error message.
### Option\#2: Using Custom Exception classes to get customized error messages
In Python, you can define your own custom exception classes by inheriting from another Exception class as shown in the code below.
```
class MyOwnException(Exception):
def __str__(self):
return 'My Own Exception has occurred'
def __repr__(self):
return str(type(self))
try:
raise MyOwnException
except MyOwnException as e:
print(e)
print(repr(e))
```
#### **How to choose the exception class to inherit from?**
In the above example, I have inherited from the *Exception* class in python, but the recommended practice is to choose a class that closely resembles your use-case.
For example, say you are trying to work with a *string* type object and you are given a *list* type object instead, here you should inherit your custom exception from *TypeError* since this Exception type closely resembles your use case which is “the variable is not of expected type”.
If you are looking for getting an appropriate Exception class to inherit from, I recommend having a look at all the built-in exceptions from the official python page [here](https://docs.python.org/3/library/exceptions.html#bltin-exceptions). For the sake of keeping this example simple, I have chosen the higher-level exception type named “*Exception*” class to inherit from.
In the code below, we are collecting values from the user and to tell the user that there is an error in the value entered we are using the *ValueError* class.
```
class EnteredGarbageError(ValueError):
def __str__(self):
return 'You did not select an option provided!'
try:
options = ['A', 'B', 'C']
x = input('Type A or B or C: ')
if x not in options:
raise EnteredGarbageError
else:
print ('You have chosen: ', x)
except EnteredGarbageError as err:
print(err)
```
Now that we understand how to choose a class to inherit from, let us next have a look at how to customize the default error messages that these classes return.
#### **How to customize the error message in our custom exception class?**
To help us achieve our purpose here which is to print some custom error messages, all objects in python come with 2 methods named *\_\_str\_\_* and *\_\_repr\_\_*. This is pronounced “dunder-str” and “dunder-repr” where “dunder” is short for “double underscore”.
**Dunder-str method**:
The method \_\_str\_\_ returns a string and this is what the built-in *print()* function calls whenever we pass it an object to print.
```
print(object1)
```
In the line above, python will call the *\_\_str\_\_* method of the object and prints out the string returned by that method.
Let us have a look at what python’s official documentation over at [python.org](http://docs.python.org/ "Python Exception Tutorial: Printing Error Messages (5 Examples!)") has to say about the **str** method.

https://docs.python.org/3/reference/datamodel.html\#object.**str**
In simpler words, **the str method returns a human-readable string for logging purposes,** **and when this information is passed to the built-in function *print()*, the string it returns gets printed.**
So since our implementation of **str** returns the string “*My Own Exception has occurred*” this string got printed on the first line of the exception message.
**Dunder-repr method**:
*\_\_repr\_\_* is another method available in all objects in python.
Where it differs from the dunder-str method is the fact that while **the *\_\_str\_\_* is used for getting a “friendly message”, the *\_\_repr\_\_* method is used for getting, a more of a, “formal message”.** You can think of str as a text you got from your friends and repr as a notice you got from a legal **repr**esentative\!
The below screenshot from [python’s official documentation](https://docs.python.org/3/reference/datamodel.html#object.repr) explains the use of *\_\_repr\_\_* method.

https://docs.python.org/3/reference/datamodel.html\#object.**repr**
Again, in simpler words, **repr** is typically used to print some “formal” or “official” information about an object in Python
In our Example 2 above, the **repr** method returned the class name using the built-in *type()* function.
Next, let us see another variation where we can print different error messages using a single Exception class without making a custom class.
### Option\#3: Custom Error messages from the raise statement
```
try:
raise Exception('I wish to print this message')
except Exception as error:
print(error)
```
Lucky for us, python has made this process incredibly simple! Just pass in the message as an argument to the type of exception you wish to raise and this will print that custom message instead\!
In the above code, we are throwing an exception of type “Exception” by calling its constructor and giving the custom message as an argument, which then overrides the default *\_\_str\_\_* method to return the string passed in.
If you wish to learn more about raise statement, I suggest reading my other article in the link below
[Python: Manually throw/raise an Exception using the “raise” statement](https://embeddedinventor.com/python-manually-throw-raise-an-exception-using-the-raise-statement/)
where I have explained 3 ways you can use the *raise* statement in python and when to use each.
**But when to use option 2 and when to use option 3?**
On the surface, Option\#3 of passing in the custom message may look like it made option\#2 of using custom classes useless. But the main reason to use Option\#2 is the fact that **Option\#2 can be used to override more than just the *\_\_str\_\_* method**.
Let’s next move on to section 2 of this article and look at how to choose a specific part of the default error message (the error printed on the console when you don’t catch an exception) and use that to make our own error messages
## Choosing Parts of Default Error Messages to print
To understand what I mean by “Default Error Message” let us see an example
```
raise ValueError("This is an ValueError")
```
This line when run, will print the following error message
```
Traceback (most recent call last):
File "<ipython-input-24-57127e33a735>", line 1, in <module>
raise ValueError("This is an ValueError")
ValueError: This is an ValueError
```
This error message contains 3 Parts
- Exception Type (ValueError)
- Error message (This is an ValueError)
- and the stack trace (the 1st few lines showing us where exactly in the program the exception has occurred)
For visual learners out there we have also made an interesting video on that topic\!
The information needed
- to extract and use each of the individual pieces of information listed above and
- when to use what piece of information
is already covered with the help of several examples in my previous article in the link below
[Python Exceptions: Getting and Handling Error Messages as strings.](https://embeddedinventor.com/python-exceptions-getting-and-handling-error-messages-as-strings/)
And with that I will end this article\!
If you are looking for another interesting read, try the article in the link below.
[Exceptions in Python: Everything You Need To Know\!](https://embeddedinventor.com/exceptions-in-python-everything-you-need-to-know/)
The above article covers all the basics of Exception handling in Python like
- when and how to ignore exceptions
- when and how to retry the problematic code that produced the exception and
- when and how to log the errors
I hope you enjoyed reading this article and got some value from it.
Feel free to share it with your friends and colleagues\! |
| Shard | 81 (laksa) |
| Root Hash | 14039567429692063881 |
| Unparsed URL | com,embeddedinventor!/python-exception-tutorial-printing-error-messages/ s443 |