TypeError: exceptions must derive from BaseException

In this article, we will discuss the TypeError: exceptions must derive from BaseException error in Python, a common error you may encounter when they try to define or raise their exceptions. We will explain this error, its causes, and how to resolve it. We will also answer frequently asked questions about Python’s error and custom exceptions.

What is the “TypeError: exceptions must derive from BaseException” error?

The TypeError: exceptions must derive from BaseException, a type of TypeError, raised when an operation or function is applied to an incompatible object. In this case, the inappropriate type is an exception class that does not inherit from the BaseException class.

The BaseException class is the base class for all exceptions in Python, and it provides some essential attributes and methods required for exception handling, such as the args attribute, the __str__ method, and the with_traceback method. All built-in exceptions in Python, such as ValueError, RuntimeError, or KeyboardInterrupt, are subclasses of BaseException, and they inherit these attributes and methods from it.

Therefore, if you try to define or raise an exception class not inherited from BaseException, the Python interpreter will reject it and raise a TypeError. This ensures the consistency and reliability of the exception-handling mechanism in Python.

For example, the following code snippet tries to define a custom exception class called MyException, which does not derive from BaseException, and then raise an instance of it:

class MyException:
    pass

raise MyException()

This code will produce the following error message:

TypeError: exceptions must derive from BaseException
TypeError: exceptions must derive from BaseException

What causes the “TypeError: exceptions must derive from BaseException” error?

The TypeError: exceptions must derive from BaseException error caused by violating the exception hierarchy in Python. According to the Python documentation, all exceptions must be instances of a class derived from BaseException. This design choice ensures that all exceptions have a common interface and behavior and can be handled uniformly by the try-except block or the except clause.

However, sometimes you may want to create custom exceptions to handle specific situations or errors not covered by the built-in exceptions. For example, you may want to create a custom exception to indicate that a file is not found or that a user has entered an invalid input. In such cases, you must ensure that the custom exception class is a subclass of BaseException or one of its subclasses, like Exception, ValueError, or RuntimeError.

If you fail to do so and tries to create or raise an exception class that does not inherit from BaseException, the Python interpreter will raise a TypeError, as shown in the previous example.

How do we resolve the “TypeError: exceptions must derive from BaseException” error?

To resolve the TypeError: exceptions must derive from BaseException you need to make sure that all custom exception classes are either subclasses of BaseException or one of its subclasses. This can be ensured by using the class statement with the name of the base class in parentheses after the name of the custom exception class.

Below is a code snippet, that can help you undertsand it better.

Syntax:

class MyException(Exception):
    pass

raise MyException()

This code will not produce any error but will raise a MyException exception, which can be caught and handled by a try-except block or propagated to the caller.

FAQs

What is the difference between BaseException and Exception in Python?

BaseException is the base class for all exceptions in Python. In contrast, Exception is the base class for most user-defined and built-in exceptions unrelated to the system or the interpreter. Generally, you should use Exception or its subclasses for their custom exceptions unless they need to handle some low-level or critical errors, such as KeyboardInterrupt, SystemExit, or MemoryError, which are subclasses of BaseException.

How can I create a custom exception in Python with a custom message or additional attributes?

To create a custom exception with a custom message or additional attributes, you can override the __init__ method of the custom exception class and assign the message or attributes to the instance. The following code snippet defines a custom exception class called MyException, that take a message and a code as argument and then raises an instance with a specific message and code:
class MyException(Exception):
def __init__(self, message, code):
super().__init__(message)
self.code = code

raise MyException("Something went wrong", 42)

The above code will raise a MyException exception with the message “Something went wrong” and code 42, which can access the args attribute and the code attribute of the exception object.

Conclusion

In this article, we have learned about the TypeError: exceptions must derive from BaseException error in Python 3, what it means, what causes it, and how to resolve it. We have also answered frequently asked questions about Python’s error and custom exceptions. 

Reference

  1. BaseException
  2. __str__

Follow Python Clear to learn more about Python.

Leave a Comment