0

I have a simple question with a likely more complicated answer.

I wrote a custom Exception class in Python:

class MyError(Exception):
  def __init__(self, message, other_info):
    Exception.__init__(self, message)
    self.other_info = other_info

What I would like to do is alter the default handling of this exception to include the information in other_info, but I want to keep it out of the main Exception message for organization's sake.

I have seen a post on how to override sys.excepthook entirely, but I don't want to change how it works -- I just want to change the way MyError is handled. Is this possible?

1
  • Perhaps you are just looking to override the __str__ method of the exception? Other than the type, which you can match in an except clause, the exception handling system doesn't really deal with the internal details of an exception object. Those details are for use by the particular handling code when you catch a specific exception. Commented Sep 10, 2013 at 14:47

1 Answer 1

2

I am trying to understand what you meant by alter the default handling and guessed that you want the exception message to display self.other_info instead of self.message. If that is the case, modify the class to add the __str__ function:

class MyError(Exception):
    def __init__(self, msg, other_info):
        Exception.__init__(self, msg)
        self.other_info = other_info
    def __str__(self):
        return '<MyError: {}>'.format(self.other_info)
        # Or, simply:
        # return self.other_info
Sign up to request clarification or add additional context in comments.

1 Comment

Good call on __str__ -- I didn't even think to use that. While this isn't exactly the kind of thing I was looking for, it will work for my needs. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.