Skip to main content

21. Exception Hierarchies

Custom exceptions should be organized into logical hierarchies for clarity and flexibility.


Example Hierarchy

class AppError(Exception): pass
class ValidationError(AppError): pass
class DatabaseError(AppError): pass

Catching base exceptions:

try:
raise DatabaseError("Connection failed")
except AppError as e:
print("Caught:", e)

Why Hierarchies?

  • Catch a broad base class when handling many errors the same way.
  • Catch specific subclasses for more targeted handling.

Practice Challenge

Create a base exception ShapeError with subclasses CircleError and SquareError. Demonstrate raising and catching them.


Wrap-Up

Organizing custom exceptions in hierarchies provides flexibility and cleaner error handling.