User-defined exceptions

Why Use Custom Exceptions?

Custom exceptions provide a way to handle specific error scenarios unique to your application. They enhance code readability and make debugging easier.

Defining a Custom Exception

To create a custom exception, define a new class that inherits from the Exception base class.

class MyCustomError(Exception):
    """Custom exception for specific error handling."""
    pass

Adding Attributes

You can add attributes to your custom exception to store additional information about the error.

class InvalidInputError(Exception):
    def __init__(self, input_value, message="Invalid input provided"):
        self.input_value = input_value
        self.message = message
        super().__init__(self.message)

Raising Custom Exceptions

You can raise custom exceptions in your code when specific conditions are met.

def validate_age(age):
    if age < 0:
        raise InvalidInputError(age, "Age cannot be negative.")

Catching Custom Exceptions

Handle custom exceptions using a try-except block.

try:
    validate_age(-1)
except InvalidInputError as e:
    print(f"Error: {e.message} (Input: {e.input_value})")

Benefits of Using Custom Exceptions

  • Clarity: Makes your error handling more descriptive.
  • Modularity: Encapsulates error handling related to specific functions or modules.
  • Maintainability: Easier to manage and update code as your application grows.

Example of a Custom Exception Hierarchy

You can create a hierarchy of custom exceptions to handle various error types within an application.

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

class DatabaseError(ApplicationError):
    """Raised for database-related errors"""
    pass

class ValidationError(ApplicationError):
    """Raised for validation errors"""
    pass