TIL: Python Exception Groups
In Python, I really want business logic to throw exception I can even group them and handle them later and I'm fine with try-except-finally.
Python 3.14.2 Documentation on 2025-12-05:
The following are used when it is necessary to raise multiple unrelated exceptions. They are part of the exception hierarchy so they can be handled with except like all other exceptions. In addition, they are recognised by except*, which matches their subgroups based on the types of the contained exceptions.
Today I learned that Python has a standard library mechanism for grouping exceptions together into a single ExceptionGroup. It’s part of the exception hierarchy, so you can catch it like other exceptions, and the except* syntax lets you handle only the exceptions you care about while the rest are re-raised.
For example, from the docs, catching all exceptions except the ValueError:
try:
raise ExceptionGroup("eg",
[ValueError(1), TypeError(2), OSError(3), OSError(4)])
except* TypeError as e:
print(f'caught {type(e)} with nested {e.exceptions}')
except* OSError as e:
print(f'caught {type(e)} with nested {e.exceptions}')
Resulting in:
caught <class 'ExceptionGroup'> with nested (TypeError(2),)
caught <class 'ExceptionGroup'> with nested (OSError(3), OSError(4))
+ Exception Group Traceback (most recent call last):
| File "<doctest default[0]>", line 2, in <module>
| raise ExceptionGroup("eg",
| [ValueError(1), TypeError(2), OSError(3), OSError(4)])
| ExceptionGroup: eg (1 sub-exception)
+-+---------------- 1 ----------------
| ValueError: 1
+------------------------------------