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

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

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


4. Custom Exception with Traceback


5. Custom Exception with Multiple Error Types


6. Custom Exception with Additional Data


7. Custom Exception with Repr Method


8. Custom Exception for Authentication Failure


9. Custom Exception for Invalid Input


10. Chaining Exceptions


Last updated