1

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
  • 29,741
  • 31
  • 97
  • 132
  • 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
  • @PeterLustig Id suggest the answer by Aditya Satyavada that's currently all the way at the bottom. – Bobdabear Aug 15 '23 at 16:48

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
  • 1,048,767
  • 296
  • 4,058
  • 3,343