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.exceptionsand its message in.message.except* ErrorTypecatches only the errors of that type inside the group; the rest keep looking for anotherexcept*. Severalexcept*blocks can run in the sametry.eg.subgroup(Type)returns a group with the errors of that type andeg.split(Type)separates those that match from those that do not.- You cannot mix
exceptandexcept*in the sametry, and inside anexcept*you cannot usereturn,breakorcontinue. - It is the basis of how
asyncio.TaskGroupreports several failures at once.
You practice it in Exception groups, The order of try, else and finally and Retries with a custom error.