11-23-2020, 08:45 PM
How to Catch and Print Exception Messages in Python
Python comes with an extensive support of exceptions and exception handling. An exception event interrupts and, if uncaught, immediately terminates a running program. The most popular examples are the, , and .
An exception will immediately terminate your program. To avoid this, you can catch the exception with a block around the code where you expect that a certain exception may occur. Here’s how you catch and print a given exception:
To catch and print an exception that occurred in a code snippet, wrap it in an indented block, followed by the command that catches the exception and saves its error message in string variable . You can now print the error message with or use it for further processing.
Example 1: Catch and Print IndexError
If you try to access the list element with index 100 but your lists consist only of three elements, Python will throw an telling you that the listindex is out of range.
Your genius code attempts to access the fourth element in your list with index 3—that doesn’t exist!
![[Image: indexing-1024x576.jpg]](https://blog.finxter.com/wp-content/uploads/2020/05/indexing-1024x576.jpg)
Fortunately, you wrapped the code in a block and printed the exception. The program is not terminated. Thus, it executes the final statement after the exception has been caught and handled. This is the output of the previous code snippet.
Example 2: Catch and Print ValueError
The arises if you try to use wrong values in some functions. Here’s an example where the is raised because you tried to calculate the square root of a negative number:
The output shows that not only the error message but also the string is printed.
Example 3: Catch and Print TypeError
Python throws the if you use indexing with the square bracket notation on an object that is not indexable. This is the case if the object doesn’t define the method. Here’s how you can catch the error and print it to your shell:
The output shows that not only the error message but also the string is printed.
I hope you’re now able to catch and print your error messages.
Summary
To catch and print an exception that occurred in a code snippet, wrap it in an indented block, followed by the command that catches the exception and saves its error message in string variable . You can now print the error message with or use it for further processing.
Where to Go From Here?
Enough theory, let’s get some practice!
To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
Practice projects is how you sharpen your saw in coding!
Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?
Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.
Join the free webinar now!
The post How to Catch and Print Exception Messages in Python first appeared on Finxter.
Python comes with an extensive support of exceptions and exception handling. An exception event interrupts and, if uncaught, immediately terminates a running program. The most popular examples are the
Code:
IndexErrorCode:
ValueErrorCode:
TypeErrorAn exception will immediately terminate your program. To avoid this, you can catch the exception with a
Code:
try/exceptTo catch and print an exception that occurred in a code snippet, wrap it in an indented
Code:
tryCode:
"except Exception as e"Code:
eCode:
"print(e)"Code:
try: # ... YOUR CODE HERE ... #
except Exception as e: # ... PRINT THE ERROR MESSAGE ... # print(e)If you try to access the list element with index 100 but your lists consist only of three elements, Python will throw an
Code:
IndexErrorCode:
try: lst = ['Alice', 'Bob', 'Carl'] print(lst[3])
except Exception as e: print(e) print('Am I executed?')Your genius code attempts to access the fourth element in your list with index 3—that doesn’t exist!
![[Image: indexing-1024x576.jpg]](https://blog.finxter.com/wp-content/uploads/2020/05/indexing-1024x576.jpg)
Fortunately, you wrapped the code in a
Code:
try/catchCode:
print()Code:
list index out of range
Am I executed?The
Code:
ValueErrorCode:
ValueErrorCode:
import math try: a = math.sqrt(-2)
except Exception as e: print(e) print('Am I executed?')The output shows that not only the error message but also the string
Code:
'Am I executed?'Code:
math domain error
Am I executed?Python throws the
Code:
TypeError object is not subscriptableCode:
__getitem__()Code:
try: variable = None print(variable[0])
except Exception as e: print(e) print('Am I executed?')The output shows that not only the error message but also the string
Code:
'Am I executed?'Code:
'NoneType' object is not subscriptable
Am I executed?I hope you’re now able to catch and print your error messages.
Summary
To catch and print an exception that occurred in a code snippet, wrap it in an indented
Code:
tryCode:
"except Exception as e"Code:
eCode:
"print(e)"Where to Go From Here?
Enough theory, let’s get some practice!
To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
Practice projects is how you sharpen your saw in coding!
Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?
Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.
Join the free webinar now!
The post How to Catch and Print Exception Messages in Python first appeared on Finxter.

