Custom Exception Hierarchy Design

Design a small exception hierarchy so callers can catch broadly or precisely, and chain causes without losing the original traceback.

PythonResilience

Code

pythonsnippet
41 lines
class AppError(Exception):
    """应用异常基类:调用方可笼统捕获。"""


class ValidationError(AppError):
    """输入不合法。"""


class ExternalServiceError(AppError):
    """下游依赖失败。"""


def parse_quantity(raw: str) -> int:
    try:
        return int(raw)
    except ValueError as exc:
        # raise ... from exc:保留原始 traceback 链
        raise ValidationError(f'quantity is not a number: {raw!r}') from exc


def fetch_inventory() -> int:
    try:
        raise TimeoutError('upstream slow')
    except TimeoutError as exc:
        raise ExternalServiceError('inventory service timed out') from exc


def main() -> None:
    for fn in (lambda: parse_quantity('abc'), fetch_inventory):
        try:
            fn()
        except ValidationError as exc:
            print('validation:', exc, '| cause:', type(exc.__cause__).__name__)
        except ExternalServiceError as exc:
            print('external:', exc, '| cause:', type(exc.__cause__).__name__)
        except AppError as exc:
            print('generic app error:', exc)


if __name__ == '__main__':
    main()

Output

Captured from a sandboxed run of this snippet in the build pipeline.

validation: quantity is not a number: 'abc' | cause: ValueError
external: inventory service timed out | cause: TimeoutError

How it works

Count the classes AppError, ValidationError and ExternalServiceError and the functions parse_quantity, fetch_inventory and main as the entire surface area of Custom Exception Hierarchy Design.

for fn in (lambda: parse_quantity('abc'), fetch_inventory) is the loop that carries the per-item work. A ValidationError, TimeoutError and ExternalServiceError is raised inside an except block, so it is conditional on that failure being handled in the first place.

Applying it

The main signature reads def parse_quantity(raw: str) -> int

Output lines are prefixed (validation:, external:, generic app error:), making each step’s effect easy to spot.

Start the program and main runs parse_quantity one after another.

Statements that matter

def parse_quantity(raw: str) -> int:
    try:
        return int(raw)
    except ValueError as exc:
        # raise ... from exc:保留原始 traceback 链
        raise ValidationError(f'quantity is not a number: {raw!r}') from exc
except ExternalServiceError as exc:
    print('external:', exc, '| cause:', type(exc.__cause__).__name__)
except ValidationError as exc:
    print('validation:', exc, '| cause:', type(exc.__cause__).__name__)

Interactive Tools for This Topic

FAQ

When is the exception raised?
Inside an `except` handler — the `ValidationError`, `TimeoutError` and `ExternalServiceError` fires only while that failure type is already being handled, not on its own trigger.
What does Custom Exception Hierarchy Design print when run?
Execute the whole file; each printed line is prefixed with a label like `validation:`, `external:`.