Anton Daneyko
Anton Daneyko

Reputation: 6512

In python, how do I get my own exception classes to be pretty printed in the shell?

What should I define in my exception class in order for the shell to print it in a meaningful way? I tried the following:

#!/usr/bin/env python3.4

class MyError(Exception):
    def __init__(self, myparam1, myparam2):
        self.myparam1 = myparam1
        self.myparam2 = myparam2


    def __str__(self):
      return 'param1: {0}, param2: {1}'.format(self.param1, self.param2)


    def __repr__(self):
        return self.__str__()


if __name__ == "__main__":
  raise MyError(1, 2)

which gives me

Traceback (most recent call last):
  File "./tmp.py", line 18, in <module>
    raise MyError(1, 2)
__main__.MyError

What I would like to see there is the result of the __str__ call.

Upvotes: 3

Views: 62

Answers (1)

khelwood
khelwood

Reputation: 59185

The __init__ method in Exception accepts an exception message as a parameter. You can call it from your __init__ method.

class MyError(Exception):
    def __init__(self, param1, param2):
        super(MyError, self).__init__('param1: {0}, param2: {1}'.format(param1, param2))

>>> raise MyError(1,2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
__main__.MyError: param1: 1, param2: 2

Or if you want to rely on the exception's __str__ method to provide the message, you can pass the exception instance itself as the message to the superclass __init__:

class MyError(Exception):
    def __init__(self, myparam1, myparam2):
        super(MyError, self).__init__(self)
        self.myparam1 = myparam1
        self.myparam2 = myparam2
    def __str__(self):
        return 'param1: {0}, param2: {1}'.format(self.myparam1, self.myparam2)
    def __repr__(self):
        return str(self)

Upvotes: 3

Related Questions