You can print exception messages in Python using the built-in try...except
block and the sys.exc_info()
function.
Using try...except
Block
The try...except
block allows you to handle exceptions gracefully. If an exception occurs within the try
block, the code within the corresponding except
block will be executed.
try:
# Code that might raise an exception
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
In this example, dividing by zero raises a ZeroDivisionError
. The except
block catches this exception and prints the error message using an f-string.
Using sys.exc_info()
Function
The sys.exc_info()
function returns information about the current exception, including the exception type, value, and traceback.
import sys
try:
# Code that might raise an exception
result = 10 / 0
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
print(f"Error type: {exc_type}")
print(f"Error value: {exc_value}")
print(f"Traceback: {exc_traceback}")
This code catches any exception and prints the exception type, value, and traceback.
Practical Insights
- You can use the
else
block within thetry...except
block to execute code only if no exception occurs. - The
finally
block executes regardless of whether an exception occurred or not. - You can specify multiple
except
blocks to handle different types of exceptions.
Examples
Here are some examples of how to print exception messages in Python:
Example 1: Printing the exception message directly
try:
# Code that might raise an exception
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
Example 2: Using the sys.exc_info()
function to get detailed information about the exception
import sys
try:
# Code that might raise an exception
result = 10 / 0
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
print(f"Error type: {exc_type}")
print(f"Error value: {exc_value}")
print(f"Traceback: {exc_traceback}")
Example 3: Handling multiple exception types
try:
# Code that might raise an exception
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: Cannot divide by zero: {e}")
except TypeError as e:
print(f"Error: Invalid data type: {e}")
except Exception as e:
print(f"Error: An unexpected error occurred: {e}")
This code handles three different exception types: ZeroDivisionError
, TypeError
, and any other exception using the Exception
class.