except* Handles Exception Groups

Split an ExceptionGroup by type with except*: each clause runs for every matching member, and unmatched types pass through untouched.

PythonResilience

Code

pythonsnippet
30 lines
# 3.11 异常组:一批操作里多个失败被捆成 ExceptionGroup 一起抛出
def validate(rows):
    errors = []
    for i, row in enumerate(rows):
        try:
            if row["qty"] <= 0:
                raise ValueError(f"row {i}: qty must be positive")
            if not row["sku"].startswith("SKU-"):
                raise KeyError(f"row {i}: sku prefix not allowed")
        except (ValueError, KeyError) as exc:
            errors.append(exc)
    if errors:
        raise ExceptionGroup("batch validation failed", errors)
    return len(rows)

rows = [
    {"sku": "SKU-1", "qty": 2},
    {"sku": "BAD-1", "qty": 1},
    {"sku": "SKU-3", "qty": -5},
    {"sku": "SKU-4", "qty": 0},
]

# except* 按类型拆组:每个子句对所有匹配成员各执行一次,未匹配类型原样穿过
try:
    validate(rows)
except* ValueError as group:
    for exc in group.exceptions:
        print("value error:", exc)
except* KeyError as group:
    print("key errors:", len(group.exceptions))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

value error: row 2: qty must be positive
value error: row 3: qty must be positive
key errors: 1

How the snippet works

except* Handles Exception Groups reduces to the function validate.

for i, row in enumerate(rows) handles the per-item repetition. A ValueError, KeyError and ExceptionGroup is raised inside an except block, so it is conditional on that failure being handled in the first place.

What to watch for

  • There is no install step; the platform already includes each API.
  • The guard row["qty"] <= 0 cuts the rest of the flow with raise when its condition holds.

Using it

The signature line to copy: def validate(rows)

The run prints tagged lines — value error:, key errors: — when the file runs.

The surface worth importing is validate; the helpers around it are private to the snippet.

Key statements

except (ValueError, KeyError) as exc:
    errors.append(exc)
except* ValueError as group:
    for exc in group.exceptions:
        print("value error:", exc)
except* KeyError as group:
    print("key errors:", len(group.exceptions))

Interactive Tools for This Topic

FAQ

When is the exception raised?
Inside an `except` handler — the `ValueError`, `KeyError` and `ExceptionGroup` fires only while that failure type is already being handled, not on its own trigger.
Do I need to install anything before running this?
No — every API used here ships with the language runtime, so there is nothing to install. The file defines `validate` at load time.