14. Custom Exceptions

These examples show how to design custom exception classes for specific error-handling scenarios, allowing for more granular and meaningful error reporting in your Python applications.

1. Basic Custom Exception

Copy

class MyCustomError(Exception):
    pass

def divide(a, b):
    if b == 0:
        raise MyCustomError("Cannot divide by zero!")
    return a / b

try:
    result = divide(10, 0)
except MyCustomError as e:
    print(f"Error: {e}")

2. Custom Exception with Custom Message

Copy

class InvalidAgeError(Exception):
    def __init__(self, age, message="Age must be greater than 0"):
        self.age = age
        self.message = message
        super().__init__(self.message)

def validate_age(age):
    if age <= 0:
        raise InvalidAgeError(age)
    print(f"Age {age} is valid.")

try:
    validate_age(0)
except InvalidAgeError as e:
    print(f"Error: {e}")

3. Custom Exception with Error Code

Copy


4. Custom Exception with Traceback

Copy


5. Custom Exception with Multiple Error Types

Copy


6. Custom Exception with Additional Data

Copy


7. Custom Exception with Repr Method

Copy


8. Custom Exception for Authentication Failure

Copy


9. Custom Exception for Invalid Input

Copy


10. Chaining Exceptions

Copy

Last updated