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

Andrew Dalke dalke at dalkescientific.com
Thu Aug 23 14:10:59 CEST 2001

Christian Tanzer:
> 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.

Paul Rubin:
>This makes sense to me.

I believe though that it's complicated to implement while not
giving much additional power.

How would it be implemented?  There would need to be a mapping
from errno to class, and you want the classes to be named DeviceFull
or similarly readable names, rather than ENOSPC.  So all C-level
code raising an exception would need to call this mapping and
construct the appropriate subclass.  And if the errno doesn't
exists, fall back to use the IOError class it uses now.

That's doable, just more complicated, but the advantage is being
able to do

except DeviceFull:
except PermissionDenied:
except TextBusy:

Now suppose you're on a system which doesn't have a TextBusy
(errno == ETXTBSY, "if one tries to exec() a file that is currently
open for writing").  Since the errno doesn't exist, should the
TextBusy subclass exist?  If it doesn't, then on some machines
there will be a NameError for TextBusy.

So to catch those problems you'll need to have a generic

def check(err):
    return errno.errcode.get(err.errno)

except IOError, err:
    if check(err) == "ETXTBSY":

Which means we're back to what we have now.

                    dalke at dalkescientific.com

More information about the Python-list mailing list