Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 15 / Topic 5 of 6

ExceptionGroup and except*

A normal try/except (Part 6) stops at the first exception. A nightly job that checks 5,000 orders should not stop at order #2 and hide the other 4,998 problems. ExceptionGroup (Python 3.11+, PEP 654) bundles several exceptions into one object you can raise; except* (note the *) catches only the exceptions of one type from the group, letting the rest flow to the next except*. Think of a teacher grading 30 exam papers: instead of stopping at the first wrong answer, they mark every paper, then group the mistakes by topic.

ORDERS = [
    {"id": "ORD-1", "amount": 1200},
    {"id": "ORD-2", "amount": -50},
    {"id": "ORD-3"},                      # no "amount" at all
    {"id": "ORD-4", "amount": 499},
    {"id": "ORD-5", "amount": 0},
]

def validate_order(order: dict) -> None:
    if "amount" not in order:
        raise KeyError(f"{order['id']}: missing 'amount'")
    if order["amount"] <= 0:
        raise ValueError(f"{order['id']}: amount must be positive, got {order['amount']}")

def validate_all(orders: list[dict]) -> None:
    errors: list[Exception] = []
    for order in orders:
        try:
            validate_order(order)
        except (KeyError, ValueError) as error:
            errors.append(error)
    if errors:
        raise ExceptionGroup(f"{len(errors)} order(s) failed validation", errors)

try:
    validate_all(ORDERS)
except* ValueError as group:
    print("Amount problems:")
    for error in group.exceptions:
        print("  -", error)
except* KeyError as group:
    print("Missing field problems:")
    for error in group.exceptions:
        print("  -", error)

Output:

Amount problems:
  - ORD-2: amount must be positive, got -50
  - ORD-5: amount must be positive, got 0
Missing field problems:
  - "ORD-3: missing 'amount'"

That extra pair of quotes around the KeyError message is not a bug in this lesson: str(KeyError("x")) always shows "x" (with quotes), because KeyError's message is really its first argument, printed with repr. ValueError and most other exceptions do not do this.

group.exceptions is a tuple of the matched exceptions. except* can run more than once for the same try (here, once for ValueError, once for KeyError), and any exception type that matches none of the except* clauses still propagates.

Nesting

ExceptionGroups can contain other ExceptionGroups, for a sub-batch inside a bigger batch. except* SomeType still finds SomeType anywhere inside the tree.

sub_group = ExceptionGroup("sub-batch failed", [ValueError("bad row 7")])
raise ExceptionGroup("nightly job failed", [sub_group, KeyError("no email")])
# except* ValueError matches it; group here is itself an ExceptionGroup
# containing just the matched branch of the tree.
You write Use it for
try: ... except Error: one job, stop at the first failure (Part 6)
raise ExceptionGroup(message, [errors]) many independent failures from one run, report all of them
except* ErrorType: handle one error type from the group; other types still propagate

๐Ÿ” Going deeper: except* cannot be mixed with a plain except in the same try. BaseExceptionGroup is the ancestor of ExceptionGroup, for the rare case of grouping BaseException subclasses like KeyboardInterrupt.

Full program: examples/05_exception_groups.py.

Read more: the official exception groups reference.

Exercise 5: Reject a batch of uploads, reporting every problem at once

Scenario: A file-upload endpoint checks 5 files. Stopping at the first bad file would hide the other problems; the user should see everything wrong in one response. What to do: Inside main():

  1. Write validate_upload(file: dict) -> None that raises TypeError(f"{file['name']}: unsupported extension .{ext}") if the lower-cased extension is not in {"png", "jpg", "jpeg", "pdf"}, else raises ValueError(f"{file['name']}: {file['size_kb']} KB exceeds 5000 KB limit") if size_kb > 5000.
  2. Write validate_batch(files: list[dict]) -> None that calls validate_upload on each file, collects every (TypeError, ValueError) into a list, and if the list is not empty raises ExceptionGroup(f"{len(errors)} file(s) rejected", errors).
  3. Call validate_batch on:
    FILES = [
        {"name": "photo.png", "size_kb": 500},
        {"name": "video.mp4", "size_kb": 500},
        {"name": "doc.pdf", "size_kb": 9000},
        {"name": "image.jpg", "size_kb": 200},
        {"name": "archive.zip", "size_kb": 50},
    ]
    
    inside a try, with except* TypeError as group: printing "Unsupported extensions:" then each error indented with " - ", and except* ValueError as group: printing "Too large:" the same way.
  4. Call validate_batch again on a single clean file ({"name": "ok.png", "size_kb": 100}) and print "Clean batch: no error raised" right after (it should not raise).

Sample output:

Unsupported extensions:
  - video.mp4: unsupported extension .mp4
  - archive.zip: unsupported extension .zip
Too large:
  - doc.pdf: 9000 KB exceeds 5000 KB limit
Clean batch: no error raised

๐Ÿ’ก Hint: group.exceptions is a tuple of the exceptions that matched that one except*; loop over it to print each one.


Show the solution to Exercise 5
"""Exercise 5: Reject a batch of file uploads, reporting every problem at once.

Shows: raising an ExceptionGroup and handling it with except*.

Run:   python ex05.py   (macOS/Linux: python3 ex05.py)
"""

ALLOWED_EXTENSIONS = {"png", "jpg", "jpeg", "pdf"}
MAX_SIZE_KB = 5000

FILES = [
    {"name": "photo.png", "size_kb": 500},
    {"name": "video.mp4", "size_kb": 500},      # bad extension
    {"name": "doc.pdf", "size_kb": 9000},       # too big
    {"name": "image.jpg", "size_kb": 200},
    {"name": "archive.zip", "size_kb": 50},     # bad extension
]


def validate_upload(file: dict) -> None:
    ext = file["name"].rsplit(".", 1)[-1].lower()
    if ext not in ALLOWED_EXTENSIONS:
        raise TypeError(f"{file['name']}: unsupported extension .{ext}")
    if file["size_kb"] > MAX_SIZE_KB:
        raise ValueError(f"{file['name']}: {file['size_kb']} KB exceeds {MAX_SIZE_KB} KB limit")


def validate_batch(files: list[dict]) -> None:
    errors: list[Exception] = []
    for file in files:
        try:
            validate_upload(file)
        except (TypeError, ValueError) as error:
            errors.append(error)
    if errors:
        raise ExceptionGroup(f"{len(errors)} file(s) rejected", errors)


def main() -> None:
    try:
        validate_batch(FILES)
    except* TypeError as group:
        print("Unsupported extensions:")
        for error in group.exceptions:
            print("  -", error)
    except* ValueError as group:
        print("Too large:")
        for error in group.exceptions:
            print("  -", error)

    validate_batch([{"name": "ok.png", "size_kb": 100}])
    print("Clean batch: no error raised")


if __name__ == "__main__":
    main()

Search the guide