rspec/rules/S5714/python/rule.adoc

53 lines
1.4 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +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 (or an old style class if you are using python 2, but this has been removed in python 3).
This rule raises an issue when the expression used in an ``++except++`` block is a boolean expression of exceptions. The result of such expression is a single exception class, which is valid but not what the developer intended.
=== 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
print("catching only TypeError")
except (ValueError or TypeError) as exception: # Noncompliant
print("Catching only ValueError")
foo = ValueError or TypeError # foo == ValueError
foo = ValueError and TypeError # foo == TypeError
----
=== 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:
print("Catching all exceptions")
----
== Resources
2021-04-28 16:49:39 +02:00
* Python documentation - https://docs.python.org/3/reference/compound_stmts.html#except[the ``++try++`` statement]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
include::highlighting.adoc[]
endif::env-github,rspecator-view[]