User-defined Exceptions: is self.args OK?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sun Apr 20 00:58:58 EDT 2008


En Thu, 17 Apr 2008 19:11:36 -0300, Petr Jakeš <petr.jakes at tpc.cz>  
escribió:

> I am trying to dig through User-defined Exceptions.  chapter 8.5 in
> http://docs.python.org/tut/node10.html
>
>
> I would like to know, if is it OK to add following line to the __init__
> method of the TransitionError class?
>
> self.args = (self.previous, self.next, self.message)

Not necesarily, but you should call the base __init__, perhaps with a  
suitable message.

Most of the time, a meaningful error message is all what I want, so I  
write:

class FooError(Exception): pass

(perhaps inheriting from ValueError or TypeError or any other more  
meaningful base error).
Then, when something wrong is detected:

     if ....:
         raise FooError, "some %s message" % foo

In your case, you appear to require more info stored in the exception. Try  
this (based on your code):

class TransitionError(Error): # I assume Error inherits from Exception?
     def __init__(self, previous, next, message):
         self.previous = previous
         self.next = next
         Error.__init__(self, previous, next, message)
         # perhaps: Error.__init__(self, message)
         # if message already contain references to
         # previous and next

raise TransitionError, (1, 2, "oops")

Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
__main__.TransitionError: (1, 2, 'oops')

-- 
Gabriel Genellina




More information about the Python-list mailing list