Python 3.11+Exceptionsconstruct
except* and exception groups
handling
except* catches exceptions inside an ExceptionGroup by type: each handler gets its own subgroup, and whatever is unhandled propagates (Python 3.11+).
Syntax
try:
...
except* ТипОшибки as eg:
...
The main trap: a single try cannot mix except and except* — that is a SyntaxError, as is a bare except* without a type. Unlike except, several handlers may run in a row, and the target always gets a group, not the exception itself: even a single error is wrapped in an ExceptionGroup, so you look at eg.exceptions. break, continue and return are not allowed inside except*.
Examples
# Python 3.11+
try:
raise ExceptionGroup('eg', [ValueError(1), TypeError(2), ValueError(3)])
except* ValueError as eg:
print(eg.exceptions) # → (ValueError(1), ValueError(3))
except* TypeError as eg:
print(eg.exceptions) # → (TypeError(2),)
# Python 3.11+
try:
raise KeyError('k')
except* KeyError as eg:
print(repr(eg)) # → ExceptionGroup('', (KeyError('k'),))
# Python 3.11+
src = 'try:\n pass\nexcept ValueError:\n pass\n' 'except* TypeError:\n pass\n'
compile(src, 'demo', 'exec') # → SyntaxError
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy