org.sonar.l10n.py.rules.python.S6468.html Maven / Gradle / Ivy
Catching ExceptionGroup
with except*
will raise a TypeError
.
Why is this an issue?
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*
.
How to fix it
Make sure to use except
when catching ExceptionGroup errors.
Code examples
Noncompliant code example
try:
...
except* ExceptionGroup: # Noncompliant: TypeError
pass
try:
...
except* (TypeError, ExceptionGroup): # Noncompliant: TypeError
pass
Compliant solution
try:
...
except ExceptionGroup:
pass
try:
...
except (TypeError, ExceptionGroup):
pass
Resources
Documentation
- PEP-654 - Forbidden combinations
© 2015 - 2024 Weber Informatics LLC | Privacy Policy