In Python 3, attempting to raise 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.
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 an object which doesn’t derive from BaseException is raised.
Noncompliant Code Example
raise "Something went wrong" # Noncompliant
class A:
pass
raise A # Noncompliant
Compliant Solution
class MyError(Exception):
pass
raise MyError("Something went wrong")
raise MyError
See