Except star

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.