5

I tried to use __repr__ method on object that inherit from Exception.

but nothing was printed!

Can anyone help explain why?

class MyException(Exception):
    def __repr__(self):
        return "MyException Object"


try:
    raise MyException()
except MyException as e:
    print(e)   # shows nothing!
Ori.B
  • 109
  • 6

1 Answers1

6

Because MyException is inheriting Exception.__str__, which is what is first consulted by print (because the implicit call is to str(e), which only falls back internally to __repr__ if __str__ doesn't exist.

Curiously, Exception.__str__ returns a blank string:

>>> str(Exception())
''

I suppose playing around with it, it returns whatever is passed to Excpetion as an argument

>>> str(Exception(1))
'1'
>>> str(Exception(None))
'None'
>>> str(Exception(None, True))
'(None, True)'

So override __str__ instead. Or better yet, in addition to:

class MyException(Exception):
    def __repr__(self):
        return "MyException Object"
    __str__ = __repr__
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172