views:

510

answers:

2

I wanted to create my own Python exception class, like this:

class MyException(BaseException):
    def __init__(self, errno, address):
        if errno == 10048:
            mess = str(address) + ' is already in use'
        else:
            mess = 'Unable to open ' + str(address)
        BaseException.__init__(mess)

but when the program got to the call to BaseException.__init__(), I got this traceback:

BaseException.__init__(mess)
TypeError: descriptor '__init__' requires a 'exceptions.BaseException' object but received a 'str'

I thought that BaseException would take any set of arguments. Also, how I am supposed to pass an 'exceptions.BaseException' object into exceptions.BaseException's constructor?

+3  A: 

You have to call the method of the base class with the instance as the first argument:

BaseException.__init__(self, mess)

To quote from the tutorial:

An overriding method in a derived class may in fact want to extend rather than simply replace the base class method of the same name. There is a simple way to call the base class method directly: just call BaseClassName.methodname(self, arguments). This is occasionally useful to clients as well. (Note that this only works if the base class is defined or imported directly in the global scope.)

As mentioned by Tony Arkles and in the documentation,

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

so you shouldn't inherit from BaseException, anyway...

hop
Thank you. This is not the first time I've forgotten to use 'self' somewhere; I'm sure it won't be the last.
Charles Anderson
This is why I prefer using super() over calling the __init__ method explicitly. If you forget the self argument to super(), you get an error immediately.
Matt Green
+3  A: 

hop has it right.

As a side note, you really should not subclass BaseException, you should be subclassing Exception instead. (Unless you really really know what you're doing)

Tony Arkles
yeah, should have mentioned that...
hop