When to use exceptions (was Re: reducing if statements...)

Christian Tanzer tanzer at swing.co.at
Wed Aug 22 04:22:19 EDT 2001


"Andrew Dalke" <dalke at dalkescientific.com> wrote:

> Christian Tanzer:
> > I'd rather use:
> >
> >    try:
> >        somemodule.func(p1, p2, p3)
> >    except somemodule.Error_foo, msg :
> >        print msg
> >        ...
> >    except somemodule.Error_bar, msg :
> >        ...
> >    ### no need for raise anymore
> 
> Turns out that in my code that this is rare.  Modules only need
> at most a couple of different exceptions.
> 
> Plus, there are some times where it's hard to make a subclass
> for each exception.  Consider the IOError exceptions raised
> by open.  Replacing the errno by a subclass for each value
> (and how many values are there?) makes things less readable, IMHO.

`how many values are there?` is the key question here.

Do you really find a named exception less readable than an arbitrary
numeric value? [If you start naming the arbitrary values you could
just as well define different exception classes for each.]

I'd strongly prefer a IOError exception hierarchy with one exception
class for each different errno value to the current situation. You
could still catch IOError, but you could also just catch the odd
DeviceFull or PermissionDenied exception and leave all others to your
caller. 

> But you did say "rather use:", which I'll expand to "rather use,
> when it makes sense:" :)

Your expansion fits my intent -- only I can't think of a situation
where an exception class with many different error codes make sense
<wink>. The only argument in favor of it is that it saves a tiny bit
of effort for the implementer. That saving is counteracted by the
increased effort each of the clients have to expend. In sum, huge
amounts of effort are wasted.

-- 
Christian Tanzer                                         tanzer at swing.co.at
Glasauergasse 32                                       Tel: +43 1 876 62 36
A-1130 Vienna, Austria                                 Fax: +43 1 877 66 92





More information about the Python-list mailing list