Python 3.11 introduced except*
and ExceptionGroup
, making it possible to handle and raise multiple unrelated exceptions
simultaneously.
In the example below, we gather multiple exceptions in an ExceptionGroup
. This ExceptionGroup
is then caught by a single
except block:
try:
exception_group = ExceptionGroup("Files not found", [FileNotFoundError("file1.py"), FileNotFoundError("file2.py")])
raise exception_group
except ExceptionGroup as exceptions:
# Do something with all the exceptions
pass
To handle differently each type of exceptions present in an ExceptionGroup
, we have to use the except*
keyword.
try:
exception_group = ExceptionGroup("Operation errors", [ValueError("Value bigger than 100"), TypeError("Type str is not allowed")])
raise exception_group
except* ValueError as v:
# Do something with only ValueErrors
pass
except* TypeError as t:
# Do something with only TypeErrors
pass
While it is possible to catch the ExceptionGroup
and BaseExceptionGroup
types with except
, a
TypeError
will be raised when this is done with except*
.