← Back to Python, page 5

python-0096 · Hard senior

Raise and handle multiple errors with ExceptionGroup, add_note and exception chaining.

raise NewError(...) from err records the original cause, so tracebacks show both. add_note (Python 3.11+) attaches context such as which record failed. ExceptionGroup bundles several independent failures, for example from validating many rows or from concurrent tasks, and except* handles each type separately.

Full answer
python
class ImportFailed(Exception):
    pass

def parse_row(i, row):
    try:
        return int(row["qty"])
    except (KeyError, ValueError) as e:
        e.add_note(f"row {i}: {row}")
        raise

def import_rows(rows):
    errors, good = [], []
    for i, row in enumerate(rows):
        try:
            good.append(parse_row(i, row))
        except (KeyError, ValueError) as e:
            errors.append(e)
    if errors:
        raise ExceptionGroup("import failed", errors)
    return good

rows = [{"qty": "3"}, {"qty": "x"}, {}, {"qty": "5"}]
try:
    import_rows(rows)
except* ValueError as eg:
    print("value errors:", [n for e in eg.exceptions for n in e.__notes__])
except* KeyError as eg:
    print("missing keys:", [n for e in eg.exceptions for n in e.__notes__])

try:
    try:
        {}["config"]
    except KeyError as e:
        raise ImportFailed("config missing") from e
except ImportFailed as e:
    print(type(e.__cause__).__name__, e.__cause__, e.__suppress_context__)

Output:

text
value errors: ["row 1: {'qty': 'x'}"]
missing keys: ['row 2: {}']
KeyError 'config' True

Each failing row gets a note naming the row, and the importer collects all failures instead of stopping at the first. The two except* clauses each receive a sub-group of the matching type, so both run. raise ... from e sets __cause__ and marks the implicit context as suppressed, and a traceback would print 'The above exception was the direct cause of the following exception'. raise ... from None hides the cause when it is noise for the caller.

python
class ImportFailed(Exception):
    pass

def parse_row(i, row):
    try:
        return int(row["qty"])
    except (KeyError, ValueError) as e:
        e.add_note(f"row {i}: {row}")
        raise

def import_rows(rows):
    errors, good = [], []
    for i, row in enumerate(rows):
        try:
            good.append(parse_row(i, row))
        except (KeyError, ValueError) as e:
            errors.append(e)
    if errors:
        raise ExceptionGroup("import failed", errors)
    return good

rows = [{"qty": "3"}, {"qty": "x"}, {}, {"qty": "5"}]
try:
    import_rows(rows)
except* ValueError as eg:
    print("value errors:", [n for e in eg.exceptions for n in e.__notes__])
except* KeyError as eg:
    print("missing keys:", [n for e in eg.exceptions for n in e.__notes__])

try:
    try:
        {}["config"]
    except KeyError as e:
        raise ImportFailed("config missing") from e
except ImportFailed as e:
    print(type(e.__cause__).__name__, e.__cause__, e.__suppress_context__)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • from err records the cause
  • add_note attaches context
  • ExceptionGroup bundles failures
  • except* handles each type
  • from None hides irrelevant causes

Common mistakes

  • Losing the original exception when re-raising
  • Stopping a batch import at the first bad row

Follow-ups

  • How do ExceptionGroups interact with TaskGroup?
  • When should a library wrap exceptions?

Tips

  • Show both except* branches