typestar

Exception groups in Python

Several failures at once, and the except* syntax that splits them.

def gather_failures():
    problems = [ValueError("bad number"), KeyError("missing"),
                ValueError("also bad")]
    raise ExceptionGroup("validation failed", problems)


try:
    gather_failures()
except* ValueError as group:
    print("values:", [str(e) for e in group.exceptions])
except* KeyError as group:
    print("keys:", [str(e) for e in group.exceptions])

try:
    gather_failures()
except ExceptionGroup as group:
    print(group.message, len(group.exceptions))

How it works

  1. ExceptionGroup carries a list of exceptions.
  2. except* handles the matching ones and re-raises the rest.
  3. TaskGroup raises these, which is why the syntax exists.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
442
Tokens
116
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 63 seconds.

Type this snippet

Step 4 of 4 in Async in depth, step 51 of 53 in Pythonic Python.

← Previous Next →