brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's except* handles each error type inside an ExceptionGroup

Python
~/tips/tip-python-except-star-exception-groups

except* ValueError as eg:

Use except* to catch some exceptions from a group and leave the others for later.

Python 3.11 can raise several unrelated errors at once, packed in an ExceptionGroup. The syntax to take them apart is except*, with a star.

def run():
    raise ExceptionGroup("batch", [ValueError("bad value"), TypeError("bad type"), ValueError("another")])

try:
    run()
except* ValueError as eg:
    print("values:", [str(e) for e in eg.exceptions])
except* TypeError as eg:
    print("types:", [str(e) for e in eg.exceptions])

Output:

values: ['bad value', 'another']
types: ['bad type']

Each except* clause gets a smaller group with only the matching errors, and all clauses can run for one raise. Whatever nothing matched is raised again afterwards. The exceptions attribute is a tuple of the errors in that smaller group.

The catch: a normal except ValueError does not catch a ValueError that sits inside a group. Raise an ExceptionGroup holding one ValueError and the plain clause misses it; only except Exception catches the group itself. You also cannot mix except and except* in the same try.

The caught group keeps its message. In Python 3.11, printing repr(eg) for the ValueError clause of a group ExceptionGroup('g', [ValueError('a'), KeyError('k')]) gives ExceptionGroup('g', [ValueError('a')]), and the KeyError that no clause matched is raised again as ExceptionGroup('g', [KeyError('k')]). Even a plain raise ValueError caught by except* arrives wrapped, as an ExceptionGroup, so use eg.exceptions there too.

Further reading: Handling exception groups with except*, Built-in ExceptionGroup

More Python tips import asyncio from enum import StrEnum, auto import pytest pytest --maxfail=2 from functools import cached_property All Python tips (107) All topics

Link