Error and Exception Handling · 8 / 20 Theory

Exception groups and except*

Usually a program stops at the first error. But sometimes —validating lots of data, running tasks in parallel— you want to accumulate all the errors and handle them together. For that Python 3.11 added ExceptionGroup and the except* syntax.

def validate(values):
    errors = []
    for v in values:
        try:
            100 // int(v)
        except (ValueError, ZeroDivisionError) as e:
            errors.append(e)
    if errors:
        raise ExceptionGroup("invalid values", errors)

try:
    validate(["5", "x", "0", "y"])
except* ValueError as g:
    print("ValueError x", len(g.exceptions))          # ValueError x 2
except* ZeroDivisionError as g:
    print("ZeroDivisionError x", len(g.exceptions))   # ZeroDivisionError x 1

try:
    raise ExceptionGroup("group", [ValueError(1), TypeError(2)])
except ExceptionGroup as eg:
    print(eg.message, [type(x).__name__ for x in eg.exceptions])   # group ['ValueError', 'TypeError']
    print(len(eg.subgroup(ValueError).exceptions))                 # 1
  • ExceptionGroup(message, list_of_errors) is an exception that contains others. Its errors are in .exceptions and its message in .message.
  • except* ErrorType catches only the errors of that type inside the group; the rest keep looking for another except*. Several except* blocks can run in the same try.
  • eg.subgroup(Type) returns a group with the errors of that type and eg.split(Type) separates those that match from those that do not.
  • You cannot mix except and except* in the same try, and inside an except* you cannot use return, break or continue.
  • It is the basis of how asyncio.TaskGroup reports several failures at once.

You practice it in Exception groups, The order of try, else and finally and Retries with a custom error.