2023-07-04 11:11:55 +02:00
This rule raises an issue when the expression used in an ``++except++`` block is a boolean expression of exceptions.
2023-05-03 11:06:20 +02:00
== Why is this an issue?
2023-07-04 11:11:55 +02:00
The only two possible types for an ``++except++``'s expression are a class deriving from ``++BaseException++``, or a tuple composed of such classes.
Trying to catch multiple exception in the same ``++except++`` with a boolean expression of exceptions may not work as intended.
The result of a boolean expression of exceptions is a single exception class, thus using a boolean expression in an ``++except++`` block will result in catching only one kind of exception.
[source,python]
----
error = ValueError or TypeError
error is ValueError # True
error is TypeError # False
2021-04-28 16:49:39 +02:00
2023-07-04 11:11:55 +02:00
error = ValueError and TypeError
error is ValueError # False
error is TypeError # True
----
2021-04-28 16:49:39 +02:00
2023-07-04 11:11:55 +02:00
*Note*: __In Python 2 it is possible to raise an exception from an old-style class that does not derive from ``++BaseException++``.__
2021-04-28 16:49:39 +02:00
2023-07-04 11:11:55 +02:00
== How to fix it
2021-04-28 18:08:03 +02:00
2023-07-04 11:11:55 +02:00
Make sure to use a tuple of the exceptions that should be caught in the ``++except++`` block.
=== Code examples
==== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,python]
2021-04-28 16:49:39 +02:00
----
try:
raise TypeError()
except ValueError or TypeError: # Noncompliant
print("Catching only ValueError")
except ValueError and TypeError: # Noncompliant
2023-07-04 11:11:55 +02:00
print("Catching only TypeError")
2021-04-28 16:49:39 +02:00
except (ValueError or TypeError) as exception: # Noncompliant
print("Catching only ValueError")
foo = ValueError or TypeError # foo == ValueError
foo = ValueError and TypeError # foo == TypeError
----
2023-07-04 11:11:55 +02:00
==== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,python]
2021-04-28 16:49:39 +02:00
----
try:
raise TypeError()
except (ValueError, TypeError) as exception:
2023-07-04 11:11:55 +02:00
print("Catching ValueError and TypeError")
2021-04-28 16:49:39 +02:00
----
2023-05-03 11:06:20 +02:00
== Resources
2021-04-28 16:49:39 +02:00
2023-07-04 11:11:55 +02:00
=== Documentation
* https://docs.python.org/3/reference/compound_stmts.html#except[the ``++try++`` statement] - Python try statement
2021-04-28 18:08:03 +02:00
2021-09-20 15:38:42 +02:00
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== Message
Rewrite this "except" expression as a tuple of exception classes
=== Highlighting
The "except"'s expression
2021-09-20 15:38:42 +02:00
endif::env-github,rspecator-view[]