Back to results for “OOP”
Python › Exception Handling

How would you design a custom exception HIERARCHY for an application, and why does this matter for how callers can catch errors at different granularities?

Advanced

Answer

Create a base application exception (e.g., AppError), then specific subclasses for different error categories (e.g., ValidationError, NotFoundError, all inheriting from AppError) — callers can catch broadly (`except AppError`) to handle ALL application errors generically, or narrowly (`except ValidationError`) for specific recovery logic, without needing to know every specific subclass upfront.
class AppError(Exception):
    pass

class ValidationError(AppError):
    pass

class NotFoundError(AppError):
    pass

try:
    validate_and_fetch(data)
except ValidationError:
    return {"error": "invalid input"}, 400
except AppError:
    return {"error": "application error"}, 500  # catches NotFoundError and any FUTURE AppError subclass too
Real-world example Designing a web API's error-handling layer so new exception types added later are automatically caught by broader existing handlers.

Common follow-ups: Why is designing a THOUGHTFUL exception hierarchy upfront valuable for a growing codebase's error handling?