Python Print Exception Message
As a Python developer, you must have encountered “errors” or “exceptions” in your Python code. These errors can be “syntax errors”, “logical errors”, or “runtime errors”. When an error takes place in Python, the interpreter raises/throws an “exception”, which can be caught/captured and handled through exception-handling techniques. “Printing exception” messages in Python is a straightforward process. When an exception is raised, the interpreter prints an error message along with the type of exception.
These articles provide the following methods to print/display exception messages in Python:
Method 1: Print Exception Messages in Python Using the “print()” Function
The “print()” function is used to print/display the exception message. This method uses the “try-except” block to catch the exception, and the “print()” function to display the error message.
The below code is used to print the exception message:
except Exception as err:
print("An error occurred:", err)
In the above code, catch any exception that occurs in the “try” block and print the error message along with the type of exception using the “print()” function.
Based on the above output, the exception message has been displayed successfully.
Method 2: Print Exception Messages in Python Using the “logging” Module
In Python, the “logging” module can also be used to print exception messages. This module provides a way to log messages and errors to a file or on the console.
To print the exception message, use the following code:
x = 'Python'
except Exception as e:
logging.error("An error occurred: %s", e)
In the above code snippet, the “logging” module is imported at the start and is used to catch any exception that occurs in the “try” block. The “logging.error()” method is used in the “except” block to log the error message along with the type of exception.
Exception message successfully displayed in the above snippet.
Method 3: Print Exception Messages in Python Using the “traceback” Module
The “traceback” module offers a way to print detailed information about an exception, including the traceback and the line number where the exception happened.
The below-given code is used to print the exception message on the console:
except Exception as e:
According to the above code, the “traceback” module is imported. After that, the “traceback.print_exc()” function is utilized in the “except” block to catch/capture and print any exception message that occurs in the “try” block.
In this output, the exception message is logged appropriately.
The “print()” function, the “logging” module, or the “traceback” module can be used along with the “try-except” block to print exception messages in Python. These methods provide an efficient way to print the exception and fix the error based on the exception message. This Python article covered a detailed guide on how to print an exception message using various ways.
Leave a Reply
You must be logged in to post a comment.