I159
I159

Reputation: 31199

Custom python Exception with custom message

I want my custom exception be able to print a custom message when it raises. I got this approach (simplifyed):

class BooError(Exception):
    def __init__(self, *args):
        super(BooError, self).__init__(*args)
        self.message = 'Boo'

But the result is not satisfy me:

raise BooError('asdcasdcasd')

Output:

Traceback (most recent call last):
  File "hookerror.py", line 8, in <module>
    raise BooError('asdcasdcasd')
__main__.BooError: asdcasdcasd

I expected something like:

...
__main__.BooError: Boo

I know about message is deprecated. But I do not know what is the correct way to customize error message?

Upvotes: 1

Views: 640

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1125068

You'll need to set the args tuple as well:

class BooError(Exception):
    def __init__(self, *args):
        super(BooError, self).__init__(*args)
        self.args = ('Boo',)
        self.message = self.args[0]

where self.message is normally set from the first args item. The message attribute is otherwise entirely ignored by the Exception class.

You'd be far better off passing the argument to __init__:

class BooError(Exception):
    def __init__(self, *args):
        super(BooError, self).__init__('Boo')

Upvotes: 2

Related Questions