How to Catch and Print Exception Messages in Python

5/5 - (4 votes)

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 IndexError, ValueError, and TypeError.

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

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 IndexError telling you that the list index is out of range.

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!

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

list index out of range
Am I executed?

🌍 Recommended Tutorial: How to Print an Error in Python?

Example 2: Catch and Print ValueError

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

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

math domain error
Am I executed?

Example 3: Catch and Print TypeError

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

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

'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 try block, followed by the command "except Exception as e" that catches the exception and saves its error message in string variable e. You can now print the error message with "print(e)" or use it for further processing.

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. 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?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming 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.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

Programmer Humor

Q: How do you tell an introverted computer scientist from an extroverted computer scientist?

A: An extroverted computer scientist looks at your shoes when he talks to you.