exception handling in complex Python programs

eliben eliben at gmail.com
Fri Aug 22 07:13:01 CEST 2008


On Aug 19, 7:34 pm, "Chris Mellon" <arka... at gmail.com> wrote:
> On Tue, Aug 19, 2008 at 12:19 PM, eliben <eli... at gmail.com> wrote:
> > Python provides a quite good and feature-complete exception handling
> > mechanism for its programmers. This is good. But exceptions, like any
> > complex construct, are difficult to use correctly, especially as
> > programs get large.
>
> > Most of the issues of exceptions are not specific to Python, but I
> > sometimes feel that Python makes them more acute because of the free-n-
> > easy manner in which it employs exceptions for its own uses and allows
> > users to do the same.
>
> Lots of people seem to have this fear. They treat exceptions like they
> would treat error codes, trying to handle any possible case around any
> particular call.
>
> This is the wrong thing to do, and it only leads to more fragile code.
> There are only 2 reasonable things to do with an exception:
> 1) handle it, by which I mean catch the exception knowing what error
> condition it signifies, and take an appropriate action to correct the
> error and
> 2) pass it up so something else has a chance at it.
>

But by 'handling', do you also mean "rethrow with better
information" ?

I feel there's an inherent clash between two 'good practices' in
exception handling:
1) Using EAFP over LBYL
2) Hiding implementation details

Consider this code, which I wrote just yesterday:

elif type in ('LinearStartAddr', 'SegmentStartAddr'):
   if len(data) != 4:
       line_error('expecting a 4-byte data field for this record type,
got %s' % len(data))
       self.data.start_address = unpack('>L', data)

This is part of a method in a class that parses a data file. I've
ended up using LBYL here, to hide an implementation detail. I could've
let the Exception from unpack propagate, but that doesn't make much
sense with "hiding implementation". So I'm throwing a more useful
exception myself.
Was wrapping the call to unpack with try/except that throws my
exception a better idea, in your opinion ? Because that makes the code
somewhat more convoluted.

Eli





More information about the Python-list mailing list