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
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
try:
raise TypeError()
except (ValueError, TypeError) as exception:
print("Catching all exceptions")
See