TypeError: exceptions must derive from BaseException [Fixed]

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
3 min

banner

# TypeError: exceptions must derive from BaseException

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.

typeerror exceptions must derive from baseexception

Here is an example of how the error occurs.

main.py
# โ›”๏ธ 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.

# Instantiate a built-in class to raise an Error

You can instantiate a built-in class like ValueError to raise an error.

main.py
my_int = -1 if my_int < 0: raise ValueError('Negative value supplied')

raise valueerror exception

You can also handle the exception by using a try/except statement.

main.py
try: raise ValueError('something went wrong.') except ValueError as e: print(e) # ๐Ÿ‘‰๏ธ "something went wrong"

using try except to handle the exception

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.

# Defining a custom exception class

There are many different Base classes you can use, but you can also define your own by inheriting from the built-in Exception class.

main.py
class BadRequest(Exception): pass try: raise BadRequest('something went wrong.') except BadRequest as e: print(e) # ๐Ÿ‘‰๏ธ "something went wrong"

define custom exception class

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.

main.py
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')

extend exception class

The if statement checks if the integer is less than 1 and raises a BadRequest exception if the condition is met.

# The hierarchy of the built-in Exception classes in Python

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.

main.py
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.

main.py
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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev