Reuse the same exception logic in Python

Takuro Goto - Nov 4 - - Dev Community

Purpose
When coding, it's essential to handle exceptions carefully. Today, I want to share a method that allows you to reuse the same exception handling logic in Python, making your code more readable and maintainable for others.

CHandling Exceptions with a Decorator
Below is a simple implementation of a decorator designed to manage exceptions consistently across different functions.

def error_handler(func):
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except FileNotFoundError as e:
            print(f"File not found: {e}")
        except ZeroDivisionError as e:
            print(f"Zero division error occurred: {e}")
        # Additional error handling can be added here
    return wrapper
Enter fullscreen mode Exit fullscreen mode

Using the Decorator

@error_handler
def read_file(filename):
    with open(filename, 'r') as file:
        # Process the file
        print(file.read())  # Example of processing the file

@error_handler
def divide_numbers(a, b):
    return a / b
Enter fullscreen mode Exit fullscreen mode

Example Calls

read_file('test.txt')  # Attempting to read a non-existent file
divide_numbers(2, 0)   # Attempting to divide by zero
Enter fullscreen mode Exit fullscreen mode

Explanation
The code defines a decorator named error_handler, which is used to manage exceptions for any decorated functions. A decorator is a higher-order function that takes another function as an argument and extends or alters its behavior without modifying the original function's code.

When the error_handler decorator is applied to a function, it wraps the function call in a try block. If the decorated function raises a FileNotFoundError or ZeroDivisionError, the decorator catches these exceptions and prints a user-friendly error message. This approach not only enhances code readability but also promotes code reuse, as the same error handling logic can be applied to multiple functions.

By employing this technique, you can create cleaner, more robust Python code that is easier for others to understand and maintain.

. . . .
Terabox Video Player