pythonexceptioninheritanceconstructor

"Error exception must derive from BaseException" when inheriting from BaseException with custom __new__ method


What's wrong with the following code (under Python 2.7.1):

class TestFailed(BaseException):
    def __new__(self, m):
        self.message = m

    def __str__(self):
        return self.message

try:
    raise TestFailed('Oops')
except TestFailed as x:
    print x

When I run it, I get:

Traceback (most recent call last):
  File "x.py", line 9, in <module>
    raise TestFailed('Oops')
TypeError: exceptions must be old-style classes or derived from BaseException, not NoneType

But it looks to me that TestFailed does derive from BaseException.


Solution

  • __new__ is a staticmethod that needs to return an instance.

    Instead, use the __init__ method:

    class TestFailed(Exception):
        def __init__(self, m):
            self.message = m
        def __str__(self):
            return self.message
    
    try:
        raise TestFailed('Oops')
    except TestFailed as x:
        print x