Custom Exception Value?

Arnaud Delobelle arnodel at googlemail.com
Fri Mar 14 20:23:20 CET 2008


On Mar 14, 6:47 pm, erikcw <erikwickst... at gmail.com> wrote:
> Hi,
>
> When I use sys.exc_info() on one of my custom exception classes, the
> "message"/value isn't returned.  But it is when I use a built in
> exception.
>
> Example:
>
> In [32]: class Test(Exception):
>    ....:     def __init__(self, x):
>    ....:         self.value = x
>    ....:     def __str__(self):
>    ....:         return repr(self.value)
>    ....:
>    ....:
> In [39]: try:
>    ....:     raise Test('mess')
>    ....: except:
>    ....:     sys.exc_info()
>    ....:
>    ....:
> Out[39]: (<class '__main__.Test'>, Test(), <traceback object at
> 0xb7802e8c>)
>
> In [40]: try:
>    ....:     1/0
>    ....: except:
>    ....:     sys.exc_info()
>    ....:
>    ....:
> Out[40]:
> (<type 'exceptions.ZeroDivisionError'>,
>  ZeroDivisionError('integer division or modulo by zero',),
>  <traceback object at 0xb78029dc>)
>
> Wy does the output of ZeroDivisionError appear in sys.exc_info() but
> for test it is just Test() (should be Test('mess') right??)

Three ways to do it right:

* Override __repr__() rather than __str__

or forget about __repr__() and instead:

* call super(Test, self).__init__(x) from within Test.__init__()

or even

* self self.args = (x,) within Test.__init__()

HTH

--
Arnaud




More information about the Python-list mailing list