Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Catch and Print Exception Messages in Python
1
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
Code:
IndexError
,
Code:
ValueError
, and
Code:
TypeError
.

An exception will immediately terminate your program. To avoid this, you can catch the exception with a
Code:
try/except
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
Code:
try
block, followed by the command
Code:
"except Exception as e"
that catches the exception and saves its error message in string variable
Code:
e
. You can now print the error message with
Code:
"print(e)"
or use it for further processing.

Code:
try: # ... YOUR CODE HERE ... # except Exception as e: # ... PRINT THE ERROR MESSAGE ... # print(e)
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
Code:
IndexError
telling you that the listindex is out of range.

Code:
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]

Fortunately, you wrapped the code in a
Code:
try/catch
block and printed the exception. The program is not terminated. Thus, it executes the final
Code:
print()
statement after the exception has been caught and handled. This is the output of the previous code snippet.

Code:
list index out of range Am I executed?
Example 2: Catch and Print ValueError

The
Code:
ValueError
arises if you try to use wrong values in some functions. Here’s an example where the
Code:
ValueError
is raised because you tried to calculate the square root of a negative number:

Code:
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?'
is printed.

Code:
math domain error Am I executed?
Example 3: Catch and Print TypeError

Python throws the
Code:
TypeError object is not subscriptable
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
Code:
__getitem__()
method. Here’s how you can catch the error and print it to your shell:

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?'
is printed.

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:
try
block, followed by the command
Code:
"except Exception as e"
that catches the exception and saves its error message in string variable
Code:
e
. You can now print the error message with
Code:
"print(e)"
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.
Reply

Users browsing this thread:
1 Guest(s)


Forum Jump: