Attempting to raise an object which does not derive from BaseException
will raise a TypeError
.
If you are about to create a custom exception class, note that custom exceptions should inherit from Exception
, rather than
BaseException
.
BaseException
is the base class for all built-in exceptions in Python, including system-exiting exceptions like
SystemExit
or KeyboardInterrupt
, which are typically not meant to be caught. On the other hand, Exception
is
intended for exceptions that are expected to be caught, which is generally the case for user-defined exceptions. See PEP 352 for more information.
To fix this issue, make sure that the object you’re attempting to raise inherits from BaseException
.
Code examples
Noncompliant code example
raise "Something went wrong" # Noncompliant: a string is not a valid exception
class A:
pass
raise A # Noncompliant: A does not inherit from Exception
Compliant solution
class MyError(Exception):
pass
raise MyError("Something went wrong")
raise MyError
Note: In Python 2 it is possible to raise old-style classes but this shouldn’t be done in order to be compatible with Python
3.