Why this matters
Catching objects that don’t inherit from `BaseException` causes a `TypeError`. Only valid exception classes should be caught.
Detect exception handling blocks that catch objects not derived from `BaseException`. This causes a `TypeError` and should be avoided.
Catching objects that don’t inherit from `BaseException` causes a `TypeError`. Only valid exception classes should be caught.
Side-by-side examples engineers can pattern-match during review.
class CustomException(object):
"""An Invalid exception class."""
pass
try:
...
except CustomException: # Noncompliant: this custom exception does not derive from BaseException or Exception.
print("exception")
try:
...
except [TypeError, ValueError]: # Noncompliant: list of exceptions, only tuples are valid.
print("exception")class CustomException(Exception):
pass
try:
...
except CustomException:
print("exception")
try:
...
except (TypeError, ValueError):
print("exception")class CustomException(object):
"""An Invalid exception class."""
pass
try:
...
except CustomException: # Noncompliant: this custom exception does not derive from BaseException or Exception.
print("exception")
try:
...
except [TypeError, ValueError]: # Noncompliant: list of exceptions, only tuples are valid.
print("exception")class CustomException(Exception):
pass
try:
...
except CustomException:
print("exception")
try:
...
except (TypeError, ValueError):
print("exception")From the same buckets as this rule.
Check if loops use equality operators (== or !=) in termination conditions. These can lead to infinite loops if the condition is never met exactly. Instead, use relational operators like < or > for safer loop termination.