Effective Error Handling in Python
Posted on June 1, 2024 (Last modified on June 8, 2024) • 2 min read • 241 wordsLearn how to handle errors and exceptions in Python effectively, including try-except blocks, custom exceptions, and logging.
Error handling is an essential aspect of robust programming. This guide will teach you how to handle errors and exceptions in Python effectively using try-except blocks, custom exceptions, and logging.
Use try-except blocks to catch and handle exceptions.
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Handle multiple exceptions in a single block.
try:
result = 10 / 0
except (ZeroDivisionError, ValueError):
print("An error occurred")
Use the finally
block to execute code regardless of the exception.
try:
file = open("example.txt", "r")
finally:
file.close()
Define your own exception classes for specific error handling.
class CustomError(Exception):
def __init__(self, message):
self.message = message
try:
raise CustomError("This is a custom error")
except CustomError as e:
print(e.message)
Custom exceptions can include additional functionality.
class CustomError(Exception):
def __init__(self, message, error_code):
super().__init__(message)
self.error_code = error_code
try:
raise CustomError("This is a custom error", 404)
except CustomError as e:
print(f"Error: {e.message}, Code: {e.error_code}")
Use logging for better error tracking and debugging.
import logging
logging.basicConfig(level=logging.DEBUG)
try:
result = 10 / 0
except ZeroDivisionError:
logging.error("Cannot divide by zero")
Logging can include different levels of severity.
logging.debug("Debug message")
logging.info("Info message")
logging.warning("Warning message")
logging.error("Error message")
logging.critical("Critical message")
Effective error handling makes your code more reliable and easier to debug. Practice using try-except blocks, custom exceptions, and logging to manage errors gracefully in your Python applications.