Best practise hierarchy for user-defined exceptions

Nick Craig-Wood nick at craig-wood.com
Mon Nov 17 15:29:57 EST 2008


Slaunger <Slaunger at gmail.com> wrote:
>  On 17 Nov., 13:05, "Chris Rebert" <c... at rebertia.com> wrote:
> > On Mon, Nov 17, 2008 at 3:47 AM, Slaunger <Slaun... at gmail.com> wrote:
> >
> > > .....
> > > Here is my stub-implemented idea on how to do it so far, which is
> > > inspired by how I would have done it in Java (but which may not be
> > > very Pythonic??):
> >
> > > class MyException(Exception):
> >
> > > ? ?pass
> >
> > The above class probably isn't necessary. You don't need to
> > overgeneralize this much.
> >
>  Seems reasonable.
> > > class MyStandardError(MyException, StandardError):
> >
> > > ? ?pass
> >
> > Rename the previous class to just MyError in light of removing the other class.
> >
> >
>  OK.
> >
> > > class MyParseError(MyStandardError, ValueError):
> >
> > > ? pass
> >
> > This technique is very Pythonic. Subclass from both the exception
> > class for your module and from a built-in one if there's an applicable
> > one.
> >
> >
>  OK. One thing I *like* about it is that I inherit properties of
>  ValueError.
> 
>  One thing I feel *a little uneasy about* is that if I do something
>  like this
> 
>  try:
>      do_something_which_raises_MyParseError_which_I_have_overlooked()
>      do_something_where_I_know_a_ValueError_can_be_raised()
>  catch ValueError:
>      handle_the_anticipated_ValueError_from_std_lib()
>  finally:
>      ....
> 
>  I will not notice that it was an unanticpated condition in my own
>  code, which caused the ValueError
>  to be raised. If I had just inherited from MyError, it would fall
>  through (which I would prefer)

I'd say if the above code worries you, then MyParseError isn't a
ValueError and you shouldn't inherit from ValueError.

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list