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

Copy

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

Copy

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

Copy


4. Custom Exception with Traceback

Copy


5. Catching Multiple Custom Exceptions

Copy


6. Re-Raising Custom Exceptions

Copy


7. Custom Exception with Context Manager

Copy


8. Custom Exception with String Representation

Copy


9. Custom Exception for Invalid Operation

Copy


10. Custom Exception for Database Error

Copy


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

Last updated