rspec/rules/S6468/python/rule.adoc
Fred Tingaud d3cfe19d7e
Fix broken or dangerous backquotes
Co-authored-by: Marco Borgeaud <89914223+marco-antognini-sonarsource@users.noreply.github.com>
2023-10-30 10:33:56 +01:00

84 lines
1.9 KiB
Plaintext

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:
[source,python]
----
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.
[source,python]
----
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
[source,python,diff-id=1,diff-type=noncompliant]
----
try:
...
except* ExceptionGroup: # Noncompliant: TypeError
pass
try:
...
except* (TypeError, ExceptionGroup): # Noncompliant: TypeError
pass
----
==== Compliant solution
[source,python,diff-id=1,diff-type=compliant]
----
try:
...
except ExceptionGroup:
pass
try:
...
except (TypeError, ExceptionGroup):
pass
----
== Resources
=== Documentation
* https://peps.python.org/pep-0654/#forbidden-combinations[PEP-654] - Forbidden combinations