Learn how to effectively handle and print exception messages in Python to improve error handling and debugging.
📌 print exception, error message python, exception str
In Python, exceptions are errors detected during execution that disrupt the normal flow of a program. Handling exceptions properly is crucial to ensure your program doesn't crash unexpectedly.
Understanding how to print exception messages is essential for debugging and logging errors in Python applications. It allows developers to identify and fix issues quickly.
To print exception messages in Python, you can use the try-except block. Inside the except block, you can use the str() function to convert the exception to a string and print it.
A common mistake is to ignore exceptions, which results in losing valuable debugging information. Always handle exceptions explicitly and print meaningful messages.
Best practices include logging exception messages using the logging module, which provides more flexibility and control over how errors are recorded and reviewed.
Ignoring exceptions without handling them
✅ Use try-except blocks to handle exceptions and print or log meaningful messages.
Catching broad exceptions
✅ Catch specific exceptions like ValueError or FileNotFoundError to handle different error scenarios more accurately.
try:
result = 10 / 0
except Exception as e:
print(str(e))This code attempts to divide by zero, which raises an exception. The except block catches the exception and prints its message using str(e).
import logging
logging.basicConfig(level=logging.ERROR)
try:
with open('file.txt', 'r') as file:
content = file.read()
except FileNotFoundError as e:
logging.error('File not found: %s', e)This example tries to open a non-existent file, catching the FileNotFoundError. It logs an error message with the exception details, demonstrating a real-world application of exception handling.