Sobes.tech
Junior — Middle

Are there structures in Python for organizing inheritance of exceptions and their hierarchy?

sobes.tech AI

Answer from AI

Yes, in Python, exceptions are organized into a hierarchical class structure, which allows creating custom exceptions by inheriting from standard or user-defined classes.

All exceptions inherit from the base class BaseException, and most commonly from Exception. This enables grouping exceptions by meaning and handling them at different levels.

Example of creating an exception hierarchy:

class MyAppError(Exception):
    pass

class DatabaseError(MyAppError):
    pass

class ConnectionError(DatabaseError):
    pass

try:
    raise ConnectionError("Database connection error")
except DatabaseError as e:
    print(f"Database error handled: {e}")

This approach helps structure error handling and makes the code more readable and maintainable.