Exception group

2 snippets in Python

PYPython

Exception Groups (3.11+)

PY · Error Handling
Syntax
raise ExceptionGroup(msg, [exc1, exc2])
except* ErrorType as eg:
Example
def validate(data: dict) -> None:
    errors = []
    if not data.get("name"):
        errors.append(ValueError("name is required"))
    if not data.get("email"):
        errors.append(ValueError("email is required"))
    if errors:
        raise ExceptionGroup("Validation failed", errors)

try:
    validate({})
except* ValueError as eg:
    for err in eg.exceptions:
        print(f"  - {err}")
Output
  - name is required
  - email is required

Note except* catches matching exceptions from the group while letting others propagate. ExceptionGroup is ideal for concurrent/batch operations that produce multiple errors.

except* for Exception Groups

PY · Modern Features
Syntax
try:
    ...
except* ErrorType as eg:
    ...
Example
import asyncio

async def task_a():
    raise ValueError("bad value")

async def task_b():
    raise TypeError("wrong type")

async def main():
    try:
        async with asyncio.TaskGroup() as tg:
            tg.create_task(task_a())
            tg.create_task(task_b())
    except* ValueError as eg:
        print(f"Value errors: {eg.exceptions}")
    except* TypeError as eg:
        print(f"Type errors: {eg.exceptions}")

# asyncio.run(main())
Output
Value errors: (ValueError('bad value'),)
Type errors: (TypeError('wrong type'),)

Note except* can match multiple handlers for the same ExceptionGroup. It splits the group so each handler gets only its matching exceptions.

Frequently asked questions

How does Python handle exception group?
Python covers this with 2 copy-ready snippets on this page. The "Exception Groups (3.11+)" snippet in Python uses `raise ExceptionGroup(msg, [exc1, exc2])`.
Which code does the Python example use?
The "Exception Groups (3.11+)" snippet uses `raise ExceptionGroup(msg, [exc1, exc2])`, from the Error Handling section of the Python cheat sheet.
What other Python snippets are shown for "exception group"?
Besides "Exception Groups (3.11+)", this page also shows "except* for Exception Groups".
Is there anything to watch out for?
Yes. For "Exception Groups (3.11+)": except* catches matching exceptions from the group while letting others propagate. ExceptionGroup is ideal for concurrent/batch operations that produce multiple errors.