In Python 3, attempting to catch in an except
statement an object which does not derive from BaseException will raise a
TypeError
. In Python 2 it is possible to raise old-style classes but this shouldn’t be done anymore in order to be compatible with Python
3.
In order to catch multiple exceptions in an except
statement, a tuple of exception classes should be provided.
If you are about to create a custom Exception class, note that custom exceptions should inherit from Exception
, not
BaseException
. Exception
allows people to catch all exceptions except the ones explicitly asking the interpreter to stop,
such as KeyboardInterrupt
and GeneratorExit
which is not an error. See PEP 352 for more information.
This rule raises an issue when the expression used in an except
statement is not a class deriving from BaseException
nor
a tuple of such classes.
Noncompliant Code Example
class CustomException:
"""An Invalid exception class."""
try:
"a string" * 42
except CustomException: # Noncompliant
print("exception")
except (None, list()): # Noncompliant * 2
print("exception")
try:
"a string" * 42
except [TypeError, ValueError]: # Noncompliant. Lists are not accepted.
print("exception")
except {TypeError, ValueError}: # Noncompliant. Sets are not accepted.
print("exception")
Compliant Solution
class MyError(Exception):
pass
try:
"a string" * 42
except (MyError, TypeError):
print("exception")
See