Browse topics

Exception groups and except*

Version
3.14
Since
3.11
Review
Draft

Summary#

An ExceptionGroup bundles exceptions so you can raise them together. Each except* clause handles the matching part of the group, so more than one clause can run for a single raise.

Syntax#

python
try:
    action()
except* ValueError as group:
    handle(group.exceptions)

errors = ExceptionGroup("message", [first_error, second_error])
matched, rest = errors.split(OSError)
raise errors

Example#

python
def validate():
    raise ExceptionGroup(
        "validation failed",
        [ValueError("bad port"), TypeError("bad name"), ValueError("bad host")],
    )


try:
    validate()
except* ValueError as group:
    print("values:", [str(error) for error in group.exceptions])
except* TypeError as group:
    print("types:", [str(error) for error in group.exceptions])

mixed = ExceptionGroup("mixed", [OSError("disk"), KeyError("id")])
matched, rest = mixed.split(OSError)
print(repr(matched))
print(repr(rest))

Expected output#

Text
values: ['bad port', 'bad host']
types: ['bad name']
ExceptionGroup('mixed', [OSError('disk')])
ExceptionGroup('mixed', [KeyError('id')])

Common mistakes#

A plain except ValueError does not match an ExceptionGroup that contains a ValueError. In an except* clause, the bound name is a group, and its exceptions can include nested groups. One try statement cannot mix except and except*. Unmatched group members propagate. split returns None for either side that has no members.

Version applicability#

Exception groups and except* were added in Python 3.11. Python 3.10 and earlier reject the except* syntax. ExceptionGroup can contain only Exception subclasses; BaseExceptionGroup can also hold other BaseException subclasses.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0