Exception groups and except*
suggest changeA normal raise reports a single error. Sometimes several unrelated errors happen at once and you want to report all of them:
- concurrent tasks where two or more fail at the same time
- validation code that checks every field and wants to report every problem, not just the first one
- cleanup code that closes several resources, where more than one
close()can fail
Python 3.11 added two features for this:
ExceptionGroup(and its base classBaseExceptionGroup) is an exception that holds a list of other exceptionsexcept*is a variant ofexceptthat handles the matching exceptions inside a group and lets the rest propagate
This article covers creating, raising and catching exception groups, how except* works, the split(), subgroup() and derive() methods, and a few practical patterns. How a group's traceback is printed is covered in Stack traces, and where ExceptionGroup sits among the built-in exceptions is shown in Exception Hierarchy.
Examples were run with Python 3.13, except the one in the Python 3.14 section.
Creating an ExceptionGroup
ExceptionGroup(message, exceptions) takes a message and a non-empty sequence of exception instances. Groups can be nested:
eg = ExceptionGroup("several things failed", [
ValueError("bad value"),
TypeError("bad type"),
ExceptionGroup("nested", [KeyError("missing"), ValueError("another")]),
])
print(repr(eg))
print(eg)
print("message:", eg.message)
print("count: ", len(eg.exceptions))
for e in eg.exceptions:
print(" ", type(e).__name__, e)
print(isinstance(eg, Exception))
ExceptionGroup('several things failed', [ValueError('bad value'), TypeError('bad type'), ExceptionGroup('nested', [KeyError('missing'), ValueError('another')])])
several things failed (3 sub-exceptions)
message: several things failed
count: 3
ValueError bad value
TypeError bad type
ExceptionGroup nested (2 sub-exceptions)
True
eg.message is the message you passed and eg.exceptions is a tuple with the direct children. A nested group is one child; it is not flattened.
The constructor validates its arguments:
for args in [("empty", []), ("not a list", ValueError("x")), ("non-exception", ["oops"])]:
try:
ExceptionGroup(*args)
except (ValueError, TypeError) as e:
print(type(e).__name__, "-", e)
g = BaseExceptionGroup("mixed", [ValueError("v"), KeyboardInterrupt()])
print(type(g).__name__)
g = BaseExceptionGroup("only exceptions", [ValueError("v")])
print(type(g).__name__)
try:
ExceptionGroup("bad", [KeyboardInterrupt()])
except TypeError as e:
print("TypeError -", e)
ValueError - second argument (exceptions) must be a non-empty sequence
TypeError - second argument (exceptions) must be a sequence
ValueError - Item 0 of second argument (exceptions) is not an exception
BaseExceptionGroup
ExceptionGroup
TypeError - Cannot nest BaseExceptions in an ExceptionGroup
There are two classes because of the split between Exception and BaseException:
ExceptionGroupsubclassesException, so it can only containExceptionsubclasses. This is the one you'll use almost always.BaseExceptionGroupcan also containKeyboardInterrupt,SystemExitandasyncio.CancelledError. If you construct aBaseExceptionGroupand all its children are regular exceptions, you automatically get anExceptionGroup.
Catching a group with plain except
An ExceptionGroup is an ordinary exception. A plain except ValueError doesn't look inside it, so it won't match a group even if every child is a ValueError:
def work():
raise ExceptionGroup("batch failed", [ValueError("row 3"), ValueError("row 7")])
try:
work()
except ValueError:
print("caught ValueError") # never runs
except ExceptionGroup as eg:
print("caught group:", eg)
for e in eg.exceptions:
print(" ", repr(e))
caught group: batch failed (2 sub-exceptions)
ValueError('row 3')
ValueError('row 7')
except ExceptionGroup (or except Exception) is the right choice when you want to handle the whole group in one place, for example to log every error. Use except* when different kinds of errors need different handling.
except*: handling the matching part of a group
except* T selects the exceptions of type T from the group, at any nesting depth, and runs the handler with a new group that contains only them. Unlike except, more than one except* clause can run for a single raise:
def work():
raise ExceptionGroup("batch failed", [
ValueError("row 3: bad number"),
KeyError("email"),
ValueError("row 7: bad date"),
ExceptionGroup("row 9", [ValueError("negative amount")]),
])
try:
work()
except* ValueError as eg:
print("ValueError handler got:", repr(eg))
except* KeyError as eg:
print("KeyError handler got: ", repr(eg))
ValueError handler got: ExceptionGroup('batch failed', [ValueError('row 3: bad number'), ValueError('row 7: bad date'), ExceptionGroup('row 9', [ValueError('negative amount')])])
KeyError handler got: ExceptionGroup('batch failed', [KeyError('email')])
Things to notice:
- the name after
asis always bound to a group, never to an individual exception - the subgroup keeps the original message and nesting:
ValueError('negative amount')is still inside therow 9group - each clause runs at most once, with all its matches together
- the clauses are tried in order, and an exception handled by an earlier clause isn't seen by later ones
As with except, you can catch several types with a tuple:
try:
raise ExceptionGroup("g", [OSError("disk full"), OSError("permission denied")])
except* (OSError, ValueError) as eg:
for e in eg.exceptions:
print("caught", repr(e))
caught OSError('disk full')
caught OSError('permission denied')
Unhandled exceptions are re-raised
When the except* clauses don't handle everything, Python re-raises a group with the leftovers after the handlers run:
try:
try:
raise ExceptionGroup("io", [ValueError("v"), OSError("disk full"), TypeError("t")])
except* ValueError:
print("handled the ValueError")
except* TypeError:
print("handled the TypeError")
except ExceptionGroup as rest:
print("not handled:", repr(rest))
handled the ValueError
handled the TypeError
not handled: ExceptionGroup('io', [OSError('disk full')])
If nothing catches the leftovers, the program ends with an exception group traceback that shows only the unhandled part:
try:
raise ExceptionGroup("io", [ValueError("v"), OSError("disk full")])
except* ValueError:
print("handled the ValueError")
handled the ValueError
+ Exception Group Traceback (most recent call last):
| File "example.py", line 2, in <module>
| raise ExceptionGroup("io", [ValueError("v"), OSError("disk full")])
| ExceptionGroup: io (1 sub-exception)
+-+---------------- 1 ----------------
| OSError: disk full
+------------------------------------
This is the main difference from catching ExceptionGroup and looking at eg.exceptions yourself: with except* you can't accidentally swallow errors you didn't write a handler for.
A plain exception is wrapped in a group
If the try block raises a normal exception, except* still works. The exception is wrapped in an ExceptionGroup with an empty message:
try:
raise ValueError("plain, not a group")
except* ValueError as eg:
print(type(eg).__name__, repr(eg))
ExceptionGroup ExceptionGroup('', (ValueError('plain, not a group'),))
So code that uses except* handles both a single exception and a group the same way. Your handler must expect a group, though: use eg.exceptions rather than treating eg as the original ValueError.
Raising inside an except* handler
An exception raised in an except* handler is not chained to the others the way it would be in an except handler. Python collects it together with the unhandled leftovers into a new group:
try:
try:
raise ExceptionGroup("upload", [ConnectionError("timeout"), ValueError("bad header")])
except* ConnectionError as eg:
raise RuntimeError("upload failed, giving up")
except ExceptionGroup as final:
print(repr(final))
ExceptionGroup('', [RuntimeError('upload failed, giving up'), ExceptionGroup('upload', [ValueError('bad header')])])
The RuntimeError still has the handled ConnectionError group as its __context__, so the traceback shows where it came from. A bare raise in an except* handler is different: Python merges the re-raised exceptions with the leftovers back into the original group, so with a bare raise in the handler above the code would see ExceptionGroup('upload', [ConnectionError('timeout'), ValueError('bad header')]), as if nothing had been caught.
Rules and restrictions
except* has a few restrictions, enforced by the compiler or at runtime:
snippets = {
"mix": "try:\n pass\nexcept* ValueError:\n pass\nexcept TypeError:\n pass\n",
"return": "def f():\n try:\n pass\n except* ValueError:\n return 1\n",
"bare": "try:\n pass\nexcept*:\n pass\n",
}
for name, src in snippets.items():
try:
compile(src, name, "exec")
except SyntaxError as e:
print(f"{name}: SyntaxError: {e.msg}")
try:
try:
raise ExceptionGroup("g", [ValueError()])
except* ExceptionGroup:
pass
except TypeError as e:
print("TypeError:", e)
mix: SyntaxError: cannot have both 'except' and 'except*' on the same 'try'
return: SyntaxError: 'break', 'continue' and 'return' cannot appear in an except* block
bare: SyntaxError: expected one or more exception types
TypeError: catching ExceptionGroup with except* is not allowed. Use except instead.
- one
trystatement uses eitherexceptorexcept*clauses, not both break,continueandreturnare not allowed in anexcept*handler, because several handlers can run and it wouldn't be clear which one decides control flow- there is no bare
except*:; to handle everything that's left, writeexcept* Exception except* ExceptionGroupis an error; use a plainexcept ExceptionGroupto catch the whole group
else and finally work with except* the same way as with except.
split() and subgroup()
except* is built on two methods you can also call yourself.
eg.subgroup(condition) returns a group with only the matching exceptions, or None if nothing matches. eg.split(condition) returns a pair (match, rest), and either part can be None. The condition is an exception type, a tuple of types, or a function that takes an exception and returns True or False:
eg = ExceptionGroup("sync", [
ConnectionError("server a"),
ValueError("bad record 12"),
ExceptionGroup("server b", [ConnectionError("reset"), ValueError("bad record 40")]),
])
network, other = eg.split(ConnectionError)
print("match:", repr(network))
print("rest: ", repr(other))
print(repr(eg.subgroup(ValueError)))
print(eg.subgroup(KeyError))
def mentions_40(e):
return "40" in str(e)
print(repr(eg.subgroup(mentions_40)))
match: ExceptionGroup('sync', [ConnectionError('server a'), ExceptionGroup('server b', [ConnectionError('reset')])])
rest: ExceptionGroup('sync', [ValueError('bad record 12'), ExceptionGroup('server b', [ValueError('bad record 40')])])
ExceptionGroup('sync', [ValueError('bad record 12'), ExceptionGroup('server b', [ValueError('bad record 40')])])
None
ExceptionGroup('sync', [ExceptionGroup('server b', [ValueError('bad record 40')])])
Both methods preserve the nesting, the messages, and the __traceback__, __cause__, __context__ and __notes__ of every group they copy. Empty nested groups are dropped.
A predicate function is called for the groups too, starting with the outer one, and not only for the leaf exceptions. If it returns True for a group, the whole group matches and its children aren't checked:
eg = ExceptionGroup("outer", [ValueError("a"), ExceptionGroup("inner", [TypeError("b")])])
def show(e):
print(" predicate called with", repr(e))
return False
eg.subgroup(show)
print(eg.subgroup(lambda e: True) is eg)
print(eg.subgroup(ValueError) is eg)
predicate called with ExceptionGroup('outer', [ValueError('a'), ExceptionGroup('inner', [TypeError('b')])])
predicate called with ValueError('a')
predicate called with ExceptionGroup('inner', [TypeError('b')])
predicate called with TypeError('b')
True
False
So a predicate like lambda e: "40" in str(e) can match a group by its message. If you only want leaves, check isinstance(e, BaseExceptionGroup) in the predicate and return False for groups.
Subclassing ExceptionGroup: derive()
You can subclass ExceptionGroup to add fields, such as the file being processed. split(), subgroup() and except* create new groups by calling self.derive(excs), and the default derive() returns a plain ExceptionGroup. Override it to keep your class and its fields:
class ImportErrors(ExceptionGroup):
def __new__(cls, message, excs, filename):
self = super().__new__(cls, message, excs)
self.filename = filename
return self
def derive(self, excs):
return ImportErrors(self.message, excs, self.filename)
eg = ImportErrors("import failed", [ValueError("row 1"), KeyError("id")], "orders.csv")
values, rest = eg.split(ValueError)
print(type(values).__name__, values.filename, repr(values.exceptions))
print(type(rest).__name__, rest.filename, repr(rest.exceptions))
try:
raise eg
except* KeyError as caught:
print("except* got", type(caught).__name__, caught.filename)
except* ValueError:
pass
ImportErrors orders.csv (ValueError('row 1'),)
ImportErrors orders.csv (KeyError('id'),)
except* got ImportErrors orders.csv
ExceptionGroup does its argument checking in __new__, so a subclass with a different signature has to override __new__ (overriding only __init__ isn't enough).
Collecting validation errors
A common use is validating input and reporting all problems in one go. Each row produces a group of field errors, and the rows are collected into an outer group. add_note() (Python 3.11+, also covered in Stack traces) records which line each group came from:
from dataclasses import dataclass
@dataclass
class Order:
id: int
email: str
quantity: int
def parse_order(row: dict) -> Order:
errors = []
try:
order_id = int(row["id"])
except KeyError:
errors.append(KeyError("id is missing"))
except ValueError as e:
errors.append(e)
email = row.get("email", "")
if "@" not in email:
errors.append(ValueError(f"invalid email: {email!r}"))
try:
quantity = int(row.get("quantity", "1"))
if quantity <= 0:
errors.append(ValueError(f"quantity must be positive, got {quantity}"))
except ValueError as e:
errors.append(e)
if errors:
raise ExceptionGroup(f"invalid order {row.get('id', '?')}", errors)
return Order(order_id, email, quantity)
def parse_all(rows: list[dict]) -> list[Order]:
orders, errors = [], []
for line, row in enumerate(rows, start=2):
try:
orders.append(parse_order(row))
except ExceptionGroup as eg:
eg.add_note(f"line {line}")
errors.append(eg)
if errors:
raise ExceptionGroup("orders.csv has errors", errors)
return orders
rows = [
{"id": "1", "email": "ann@example.com", "quantity": "2"},
{"id": "2", "email": "bob.example.com", "quantity": "0"},
{"email": "cat@example.com", "quantity": "x"},
]
def leaves(eg, notes=()):
"""Yield (exception, notes) for every non-group exception in eg."""
notes = notes + tuple(getattr(eg, "__notes__", ()))
for e in eg.exceptions:
if isinstance(e, BaseExceptionGroup):
yield from leaves(e, notes)
else:
yield e, notes
try:
parse_all(rows)
except ExceptionGroup as eg:
print(eg)
for e, notes in leaves(eg):
print(f" {', '.join(notes)}: {type(e).__name__}: {e}")
try:
parse_all(rows)
except* KeyError as eg:
print("missing fields:", len(list(leaves(eg))))
except* ValueError as eg:
print("bad values:", len(list(leaves(eg))))
orders.csv has errors (2 sub-exceptions)
line 3: ValueError: invalid email: 'bob.example.com'
line 3: ValueError: quantity must be positive, got 0
line 4: KeyError: 'id is missing'
line 4: ValueError: invalid literal for int() with base 10: 'x'
missing fields: 1
bad values: 3
There's no built-in way to iterate over all leaf exceptions, so a small recursive helper like leaves() is worth keeping around. Notice that the notes survived the split done by except*: the subgroups are created with derive() and the notes are copied over.
The first except handles the whole group to print a report. The second shows except* sorting the same errors by type. Only raise a group when there really can be several errors. Functions that fail on the first problem should keep raising a single exception, because callers find that easier to handle.
Errors while cleaning up
The same pattern works when you must try every step even if some fail, for example closing several resources:
class Resource:
def __init__(self, name, fail=False):
self.name, self.fail = name, fail
def close(self):
if self.fail:
raise OSError(f"could not close {self.name}")
print("closed", self.name)
def close_all(resources):
errors = []
for r in resources:
try:
r.close()
except Exception as e:
errors.append(e)
if errors:
raise ExceptionGroup("errors while closing", errors)
try:
close_all([Resource("db"), Resource("cache", fail=True),
Resource("log"), Resource("socket", fail=True)])
except* OSError as eg:
for e in eg.exceptions:
print("warning:", e)
closed db
closed log
warning: could not close cache
warning: could not close socket
Without a group you'd have to choose between stopping at the first failure (and leaking the remaining resources) and raising only one of the errors (and losing the others).
Exception groups from asyncio.TaskGroup
asyncio.TaskGroup is the main source of exception groups in the standard library. When tasks in the group fail, it cancels the remaining tasks and raises an ExceptionGroup with every error, so except* is the natural way to handle them:
import asyncio
async def fetch(name, delay, error=None):
await asyncio.sleep(delay)
if error:
raise error
return f"{name}: ok"
async def main():
try:
async with asyncio.TaskGroup() as tg:
tg.create_task(fetch("users", 0.1, ConnectionError("users: refused")))
tg.create_task(fetch("orders", 0.1, ValueError("orders: bad JSON")))
tg.create_task(fetch("stats", 1.0))
except* ConnectionError as eg:
print("network:", [str(e) for e in eg.exceptions])
except* ValueError as eg:
print("data: ", [str(e) for e in eg.exceptions])
asyncio.run(main())
network: ['users: refused']
data: ['orders: bad JSON']
Both failing tasks finished before the group could cancel anything, so both errors are reported, and stats was cancelled. A TaskGroup raises a group even when only one task fails, so except ConnectionError would not catch it here. Cancellation and timeouts with a TaskGroup are covered in Cancellation and timeouts, and TaskGroup itself in Structured concurrency with asyncio.TaskGroup.
Python 3.14: except without parentheses
Unrelated to groups, but easy to confuse with them: before Python 3.14, catching several types required parentheses, except (ValueError, TypeError):. Python 3.14 (PEP 758) lets you leave them out, for both except and except*, as long as you don't use as:
import json
def load(text):
try:
return json.loads(text)
except ValueError, TypeError:
return None
print(load('{"a": 1}'), load("{oops"), load(None))
try:
raise ExceptionGroup("g", [KeyError("k"), IndexError(5)])
except* KeyError, IndexError:
print("caught a lookup error")
{'a': 1} None None
caught a lookup error
With as, the parentheses are still required. except ValueError, TypeError as e: is a SyntaxError ("multiple exception types must be parenthesized when using 'as'"), and on 3.13 and older every unparenthesized form is a SyntaxError. This is not Python 2's except ValueError, e:, where the second name was the variable.
Exception groups on Python 3.10 and older
The exceptiongroup package backports ExceptionGroup and BaseExceptionGroup, with split(), subgroup() and derive(). It can't add the except* syntax, so it provides a catch() context manager that maps exception types to handler functions:
import sys
from exceptiongroup import catch
if sys.version_info < (3, 11):
from exceptiongroup import ExceptionGroup
def on_value_error(eg):
print("ValueErrors:", [str(e) for e in eg.exceptions])
def on_key_error(eg):
print("KeyErrors:", [str(e) for e in eg.exceptions])
with catch({ValueError: on_value_error, KeyError: on_key_error}):
raise ExceptionGroup("batch", [ValueError("a"), KeyError("b"), ValueError("c")])
ValueErrors: ['a', 'c']
KeyErrors: ["'b'"]
This was run on Python 3.10 with exceptiongroup 1.3.1. On 3.11 and newer the package uses the built-in classes, so libraries that support both old and new Pythons, such as anyio and trio, can raise and catch the same groups.
Summary
ExceptionGroup(msg, [exc, ...])bundles several exceptions;.messageand.exceptionsgive you the parts- a plain
except ValueErrordoes not match a group; catchExceptionGroupto handle the whole group except* Thandles theTexceptions at any depth, severalexcept*clauses can run, and the unhandled rest is re-raisedsplit()andsubgroup()filter a group while keeping its structure and metadata; overridederive()in subclasses- raise a group only when there really can be several independent errors, such as validation, cleanup and concurrent tasks