Exception groups
An exception group is a single exception that carries several independent errors at once. except* handles one type out of the group and leaves the rest for later clauses. The feature arrived in Python 3.11.
Detailed Explanation
Ordinary except assumes one failure. That matches a linear try block. It does not match "run three tasks, two of them failed". Before 3.11, libraries wrapped extra errors on __context__ or returned a list, and one traceback hid the others.
ExceptionGroup (and BaseExceptionGroup) is a builtin that holds a message and a sequence of sub-exceptions. Raising it delivers every error to the caller together. asyncio.TaskGroup and asyncio.gather(..., return_exceptions=False) use this: if two tasks fail, you receive a group, not whichever finished last.
Handling uses except*. except* ValueError as eg: matches any ValueError (and subclasses) inside the group, binds an ExceptionGroup of just those matches to eg, and unwraps them from the original group. A later except* KeyError sees what remains. If leftovers remain after every clause, they are re-raised as a group. except* does not catch a lone ValueError that is not wrapped; it only matches groups. For a single exception, keep using except.
You can mix them in one try: except ValueError for a naked error, except* ValueError for grouped ones. They are different statements with different matching rules. A clause cannot be both.
ExceptionGroup is for sibling failures that happened in parallel or in a batch. It is not for wrapping a cause. A parser that fails for one reason still raises one ValueError. A test runner that collected five assertion failures, or a shutdown that failed to close three sockets, is a group.
BaseExceptionGroup can contain KeyboardInterrupt and SystemExit. Prefer ExceptionGroup unless you are writing a runner that must forward those.
Creating one is raise ExceptionGroup("close failed", [exc1, exc2]). Nested groups are allowed; except* flattens matching types across the tree. eg.exceptions is the tuple of remaining children. eg.subgroup(predicate) and eg.split(predicate) filter without handling.
Code Examples
def close_all(errors: list[Exception]) -> None:
if errors:
raise ExceptionGroup("close failed", errors)
try:
close_all([ValueError("bad fd"), TypeError("not a socket")])
except* ValueError as eg:
print("value", eg.exceptions)
except* TypeError as eg:
print("type", eg.exceptions)
# value (ValueError('bad fd'),)
# type (TypeError('not a socket'),)# A single non-group is not matched by except*.
try:
raise ValueError("alone")
except* ValueError:
print("grouped")
except ValueError:
print("single") # singleimport asyncio
async def boom(name: str) -> None:
raise RuntimeError(name)
async def main() -> None:
try:
async with asyncio.TaskGroup() as tg:
tg.create_task(boom("a"))
tg.create_task(boom("b"))
except* RuntimeError as eg:
print(len(eg.exceptions)) # 2
# asyncio.run(main())Common Gotchas
`except` does not unpack a group
`except RuntimeError` misses a group of `RuntimeError`s. Use `except*` when the callee can raise `ExceptionGroup`.
Leftovers are re-raised
if you handle `ValueError` and a `TypeError` remains, the caller still sees a group. Handle every type you must swallow.
Requires Python 3.11+
`except*` is a syntax error on older versions.