How to Catch and Print Exception Messages in Python?

An exception refers to an error or unexpected event that arises while a program is executing in Python. This error breaks the normal flow execution of the Python program. The program stops the execution process and raises an error message that defines the problem/error.

The “try-except” method is utilized to catch and print the exceptions. An exception is thrown when code within the try block raises an exception, and the except block is utilized to handle that exception.

This post will deliver a thorough guide on capturing and displaying exception messages in Python.

How to Get and Print/Display Python Exception Messages?

The “try-except” block is utilized in Python to catch and print the exception messages. Let’s see different examples of how to get and display exception messages.

Example 1: Catch and Print ValueError

The below code is used to catch and print the ValueError:

Code:

try:
    dict_value = {}
    output = min(dict_value)
    print(output)
except Exception as x:
    print(x)
  • In the try block, the “min()” function is applied on an empty sequence.
  • In the except block, the print () function prints the exception messages.

Output:

The exception message has been shown in the above snippet.

Example 2: Catch and Print IndexError

The below code is used to catch and print the exception message for the IndexError:

Code:

try:
    list_value = ['Joseph', 'Alex', 'Lily']
    print(list_value[5])
except Exception as x:
    print(x)
  • The “IndexError” exception arises in the “try” block.
  • To handle the “IndexError” exception, the “except” block is used in the program.

Output:

The IndexError exception has been shown in the above output.

Example 3: Catch and Print TypeError

The following code is used to catch and print the “TypeError” exception:

Code:

try:
    list_value = [45, 25, 15]
    output = 22 + list_value
    print(output)
except Exception as x:
    print(x)
  • The “TypeError” arises in the above code when the “+” operator is used to add an integer and a list.
  • To catch and show the exception message, the except block is used in the program.

Output:

The above snippet shows the exception.

Example 4: Using raise Exception to Catch and Print Exception Messages

Use the “raise” keyword to raise/throw an exception based on a specific condition. The below code uses the “raise” exception technique to catch and print exception message:

Code:

if len('John') == len('Joseph'):
    print('True')
else:
    raise Exception ('String Length is Not Equal')

The “else” statement executes the “raise Exception” expression when the string length is not equal to each other.

Output:

The exception has been successfully shown in the above output.

Example 5: Catch and Print Exception Using try and logger.exception

Python’s logging module provides a method called “logger.exception” that logs an error message along with the full traceback information of an exception. It can be used to log exceptions at the point they occur in a program and automatically adds the traceback information to the log message.

The below code uses the “try and logger.exception” to catch and print the exception messages:

Code:

import logging
logger=logging.getLogger()
try:
    print("Result: ", 56/0)
except Exception as e:
    logger.exception("Exception Occurred:  " + str(e))
  • The “logging” module is imported into the program.
  • The object named “logger” is created using the “getLogger()” method of the logging module. 
  • The logger object is used to write the log messages to a file, console, etc.
  • An exception is raised when the number “56” is divided by “0” in the program.
  • The “logger.exception()” method generates a log message with the error message and traceback information. 

Output:

The “division by zero” exception has been raised.

Conclusion

To catch and print the exception messages, the “try-except” block, “raise Exception”, and “logger.exception()” method is used in Python. The try block executes the statement, except block catch, and prints the exception message on the output console. Similarly, the “raise Exception” shows the specified message when the exception is raised manually. This Python blog provided an in-depth overview of how to catch and print exception messages.