Custom Exception Value?

E

erikcw

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??)

Thanks!
 
A

Arnaud Delobelle

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,150
Members
46,697
Latest member
AugustNabo

Latest Threads

Top