Home > OS >  Multiple Inheritance: Exceptions
Multiple Inheritance: Exceptions

Time:08-03

I am designing some custom exceptions in my python project. Suppose they are called Foo, Bar, and Oat. They are all exception classes that stand independently as their own Python files.

Foo inherits from BaseException:

class Foo(BaseException):
    pass

I am getting a Python exception indicating that I must inherit from BaseException in order to use the raise keyword with this object (i.e. raise the exception).

I get this Python exception in bar.py which is an exception that inherits from foo.py. Because bar.py does not directly inherit from BaseException, is it incorrectly designed?

Do I need every Python exception to directly inherit from BaseException? Or is there a way to implement multiple inheritance?

Foo <--- Bar <--- Oat [Inheritance where Apple  <--(is-a)-- Fruit]

For further clarification although someone has detailed in the comments...

def Foo(BaseException):
    pass
def Bar(Foo):
    pass
def Oat(Bar):
    pass

The issue was that when I call raise Bar my program fails saying Bar cannot be called as it needs to be derived from BaseException.

CodePudding user response:

You must inherit from BaseException, but it doesn't have to be your direct ancestor. It just needs to be somewhere up the chain.

That's completely unremarkable. In fact, almost all exceptions in the standard library are not direct ancestors of Exception:

enter image description here

Actually, most exceptions should derive from Exception, not BaseException. See Inheriting from BaseException vs Exception

So this is perfectly reasonable:

foo.py

class Foo(Exception):
    pass

bar.py

class Bar(Foo):
    pass

oat.py

class Oat(Bar):
    pass

CodePudding user response:

The documentation explicitly states twice that user-defined exceptions should inherit from Exception, not BaseException.

exception BaseException

The base class for all built-in exceptions. It is not meant to be directly inherited by user-defined classes (for that, use Exception)....

(https://docs.python.org/3/library/exceptions.html#BaseException)

and

exception Exception

All built-in, non-system-exiting exceptions are derived from this class. All user-defined exceptions should also be derived from this class.

(https://docs.python.org/3/library/exceptions.html#Exception)

The exception refers to the attempt to raise a value that is not ultimately derived from BaseException:

>>> raise "Foo"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: exceptions must derive from BaseException
  • Related