TypeError: exceptions must derive from BaseException

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

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 raise 'something went wrong'

Exceptions must be a 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.

main.py
try: raise ValueError('something went wrong') except ValueError as e: print(e) # 👉️ "something went wrong"

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"

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 try: raise BadRequest('something went wrong') except BadRequest as e: print(e) # 👉️ "something went wrong"

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.

Conclusion #

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.

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.