0

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?

I159
  • 27,484
  • 29
  • 93
  • 128
  • 5
    In what way does the result not satisfy you? What is the result you want? – BrenBarn Jan 15 '14 at 18:59
  • maybe add a `return self.message` statement at the bottom of the `__init__` method? This is probably bad style, but might work :) – Peter Lustig Jan 15 '14 at 19:07
  • http://stackoverflow.com/questions/6180185/custom-python-exceptions-with-error-codes-and-error-messages seems to contain the answer you are looking for! – Peter Lustig Jan 15 '14 at 19:09

1 Answers1

2

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')
Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187