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?

4
  • 5
    In what way does the result not satisfy you? What is the result you want? Commented Jan 15, 2014 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 :) Commented Jan 15, 2014 at 19:07
  • stackoverflow.com/questions/6180185/… seems to contain the answer you are looking for! Commented Jan 15, 2014 at 19:09
  • @PeterLustig Id suggest the answer by Aditya Satyavada that's currently all the way at the bottom. Commented Aug 15, 2023 at 16:48

1 Answer 1

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')
Sign up to request clarification or add additional context in comments.

2 Comments

Why not pass it as parameter of super init?
Alternatively, he could just do super(BooError, self).__init__('Boo')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.