121. Custom Exception Handling

Here are 10 Python code snippets demonstrating how to create and use custom exceptions for specific error scenarios:


1. Basic Custom Exception

class CustomError(Exception):
    """Base class for other exceptions"""
    pass

def check_value(value):
    if value < 0:
        raise CustomError("Value cannot be negative")

try:
    check_value(-1)
except CustomError as e:
    print(f"Error: {e}")

2. Custom Exception with Message

class ValueTooLowError(Exception):
    def __init__(self, message="Value is too low"):
        self.message = message
        super().__init__(self.message)

def process_value(value):
    if value < 10:
        raise ValueTooLowError("Value must be greater than or equal to 10")
    return value * 2

try:
    result = process_value(5)
except ValueTooLowError as e:
    print(f"Error: {e}")

3. Custom Exception with Additional Attributes


4. Custom Exception with Traceback


5. Catching Multiple Custom Exceptions


6. Re-Raising Custom Exceptions


7. Custom Exception with Context Manager


8. Custom Exception with String Representation


9. Custom Exception for Invalid Operation


10. Custom Exception for Database Error


These snippets showcase different ways to create, use, and extend custom exceptions in Python to handle specific error scenarios effectively.

Last updated