79 lines
2.1 KiB
Plaintext
79 lines
2.1 KiB
Plaintext
This rule raises an issue when the expression used in an ``++except++`` block is a boolean expression of exceptions.
|
|
|
|
== Why is this an issue?
|
|
|
|
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
|
|
|
|
error = ValueError and TypeError
|
|
error is ValueError # False
|
|
error is TypeError # True
|
|
----
|
|
|
|
*Note*: __In Python 2 it is possible to raise an exception from an old-style class that does not derive from ``++BaseException++``.__
|
|
|
|
== How to fix it
|
|
|
|
Make sure to use a tuple of the exceptions that should be caught in the ``++except++`` block.
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,python]
|
|
----
|
|
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
|
|
|
|
[source,python]
|
|
----
|
|
try:
|
|
raise TypeError()
|
|
except (ValueError, TypeError) as exception:
|
|
print("Catching ValueError and TypeError")
|
|
----
|
|
|
|
== Resources
|
|
|
|
=== Documentation
|
|
|
|
* https://docs.python.org/3/reference/compound_stmts.html#except[the ``++try++`` statement] - Python try statement
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Rewrite this "except" expression as a tuple of exception classes
|
|
|
|
|
|
=== Highlighting
|
|
|
|
The "except"'s expression
|
|
|
|
|
|
endif::env-github,rspecator-view[]
|