Last updated: Apr 8, 2024
Reading timeยท3 min
The Python "TypeError: exceptions must derive from BaseException" occurs when
we raise an exception that is not an instance of a class that inherits from the
built-in Exception
class.
To solve the error, use a built-in error class, e.g.
raise ValueError('message')
or define your own.
Here is an example of how the error occurs.
# โ๏ธ TypeError: exceptions must derive from BaseException value = 'bobbyhadz.com' if not isinstance(value, bool): raise 'Expected a boolean value'
We used a raise
statement with a string which caused the error.
Exceptions must be classes or instances created from classes that inherit from
the Exception
class.
You can instantiate a built-in class like ValueError
to raise an error.
my_int = -1 if my_int < 0: raise ValueError('Negative value supplied')
You can also handle the exception by using a try/except statement.
try: raise ValueError('something went wrong.') except ValueError as e: print(e) # ๐๏ธ "something went wrong"
The try
block raises a ValueError
exception which is then handled by the
except
block.
If you don't handle the exception using a try/except
statement, the Python
interpreter exits and the program stops running.
The example uses the ValueError
class, however, other common exception classes
are TypeError
, StopIteration
, ReferenceError
, etc.
You can view all of the available exception classes in this section of the docs.
There are many different
Base classes
you can use, but you can also define your own by inheriting from the built-in
Exception
class.
class BadRequest(Exception): pass try: raise BadRequest('something went wrong.') except BadRequest as e: print(e) # ๐๏ธ "something went wrong"
Notice that we can handle the custom error in the except
block.
All built-in, non-system-exiting exceptions are derived from the Exception class and it should also be used for user-defined exceptions.
Here is a very simple implementation of a custom exception class.
class BadRequest(Exception): def __init__(self, message): self.message = message super().__init__(message) def __str__(self): return self.message my_int = -1 if my_int < 0: raise BadRequest('Negative value supplied')
The if
statement checks if the integer is less than 1
and raises a
BadRequest
exception if the condition is met.
All of the built-in exception classes are a subclass of BaseException
.
As the error message states: "TypeError: exceptions must derive from BaseException".
The Exception
class is a subclass of the BaseException
class.
As the
documentation states,
all user-defined exceptions should be derived from the Exception
class.
The Exception
class is the base class of all non-fatal exceptions.
Exceptions that are not subclasses of Exception
are considered fatal because
they are typically not handled.
These exceptions are used to terminate the program.
Examples of fatal exceptions include sys.exit()
and KeyBoardInterrupt
which
is raised when the user chooses to interrupt the program.
In other words, all non-fatal exception classes should extend from Exception
and not from BaseException
.
If you don't handle an exception using a try/except
statement, the program
stops and the Python interpreter exits.
raise ValueError('Something went wrong.') print('this never runs')
The print() statement in the example is never reached.
You can use a try/except
statement if you need to handle an exception, so the
program continues to run.
try: raise ValueError('Something went wrong.') except ValueError as e: print(e) # ๐๏ธ Something went wrong print('this runs โ ')
The try
block raises a ValueError
exception which is then handled by the
except
block.
The program continues to run and the print()
function prints the message.
Check out the built-in base classes before defining your own exceptions.
They cover many different errors, and you might not have to define your own.
You can learn more about the related topics by checking out the following tutorials: