How to Print Exception Messages in Python (Try-Except)

Python comes with extensive support for 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)

Next, I’ll guide you through 13 hand-picked examples for specific scenarios such as with or without traceback. Exception printing is more powerful than you’d think! Let’s get started! πŸ‘‡

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.

Example 4: Python Print Exception Message with str()

Use a try/except block, the code attempts to execute a statement and, if an exception arises, it captures and displays the corresponding error message using Python’s built-in str() function, aiding in the identification and resolution of issues.

try:
    x = undefined_variable
except Exception as e:
    print(str(e))

In this code, we reference an undefined variable, which will raise a NameError. The error message is then printed. Note that this is semantically equivalent to print(e) which internally calls str(e) to find a string representation of e.

Output:

name 'undefined_variable' is not defined

Example 5: Python Print Exception Traceback

By using the traceback module, you can retrieve and print the entire traceback of an exception, offering a comprehensive view of where the error occurred and the call stack that led to it.

import traceback

try:
    open("nonexistent_file.txt")
except Exception:
    print(traceback.format_exc())

Here, we attempt to open a non-existent file, which will raise a FileNotFoundError. The traceback is printed, providing detailed error information.

Output:

Traceback (most recent call last):
...
FileNotFoundError: [Errno 2] No such file or directory: 'nonexistent_file.txt'

Example 6: Python Print Exception Stack Trace

Printing the stack trace in Python involves using the traceback module to display the path taken by the code up to the point where the exception was raised. This method is particularly useful for understanding the sequence of function calls that led to the error, providing a clear view of the execution flow and aiding developers in pinpointing the origin of issues.

import traceback

try:
    list_of_numbers = [1, 2, 3]
    print(list_of_numbers[3])
except Exception:
    print(traceback.print_stack())

In this example, we attempt to access an index of a list that does not exist, which will raise an IndexError. The stack trace is printed, showing the path taken to the error.

Output:

A stack trace leading up to the error point.

Example 7: Python Print Exception Name

Printing the exception name involves capturing the exception and using type(e).__name__ to retrieve and display the name of the exception type. This method provides clear information about the kind of error that occurred, such as TypeError, and is useful for logging and debugging purposes.

try:
    "string" + 1
except Exception as e:
    print(type(e).__name__)

In this code, we attempt to concatenate a string and an integer, which will raise a TypeError. The name of the exception type is printed.

Output:

TypeError

Example 8: Python Print Exception Type

Displaying the exception type in Python is achieved by capturing the exception and utilizing type(e) to retrieve and print the type of exception that occurred. This method provides a clear understanding of the error category, aiding in debugging and error logging.

try:
    {}["key"]
except Exception as e:
    print(type(e))

Here, we attempt to access a non-existent key in a dictionary, which will raise a KeyError. The type of the exception is printed.

Output:

<class 'KeyError'>

Example 9: Python Print Exception Details

Printing detailed exception information in Python involves capturing the exception and utilizing string formatting to display both the name and the message of the exception. This approach provides a detailed error report, offering insights into the type of error and the accompanying message.

try:
    [] + "string"
except Exception as e:
    print(f"Error: {type(e).__name__}, Message: {str(e)}")

In this example, we attempt to add a list and a string, which will raise a TypeError. Both the name and the message of the exception are printed.

Output:

Error: TypeError, Message: can only concatenate list (not "str") to list

Example 10: Python Print Exception Line Number

Revealing the line number where an exception was raised in Python can be achieved using the sys module. By utilizing sys.exc_info()[-1].tb_lineno, developers can retrieve and print the line number where the exception occurred, providing a precise location of the issue in the code.

import sys

try:
    x = y
except Exception as e:
    print(f"Error on line {sys.exc_info()[-1].tb_lineno}: {str(e)}")

In this code, we reference an undefined variable y, which will raise a NameError. The line number and the error message are printed.

Output:

Error on line [line_number]: name 'y' is not defined

Example 11: Python Print Exception Message Without Traceback

Printing the error message without displaying the traceback in Python involves capturing the exception and using the print() function to display the error message. This method provides a clean and concise error message without additional debug information.

try:
    x = {}
    x.append(1)
except Exception as e:
    print(e)

Here, we attempt to use the append method (which is not applicable for dictionaries) on a dictionary, which will raise an AttributeError. The error message is printed without traceback.

Output:

'dict' object has no attribute 'append'

Example 12: Python Print Exception and Continue

Printing the exception and continuing the execution involves using a try/except block to manage errors without halting the entire program. By capturing and printing the exception, developers can inform users or log the error while allowing the program to continue running subsequent code.

try:
    x = 1 / 0
except Exception as e:
    print(e)
print("Program continues...")

In this example, we attempt to perform a division by zero, which will raise a ZeroDivisionError. The error message is printed, but the program continues to execute subsequent code.

Output:

division by zero
Program continues...

Example 13: Python Print Exception in One Line

Printing the exception in a single line of code in Python involves utilizing string formatting within the print() function to display a succinct and clear error message. This method maintains a compact code structure while ensuring that errors are logged or displayed.

try:
    x = [1, 2, 3]
    x[5]
except Exception as e:
    print(f"An error occurred: {e}")

In this code, we attempt to access an index of a list that does not exist, which will raise an IndexError. The error message is printed in a single line.

Output:

An error occurred: list index out of range

These examples illustrate various methods to handle and print exception information in Python, each providing a unique approach to managing errors and debugging code. The explanations, code snippets, and outputs provide a comprehensive guide to implementing these methods in Python programming.

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.

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.

πŸ§‘β€πŸ’» Recommended: Python One Line Exception Handling