EAFP vs LBYL (was Re: A little disappointed so far)

Donn Cave donn at u.washington.edu
Mon May 19 13:25:06 EDT 2003


Quoth VanL <vlindberg at verio.net>:
| Alex Martelli wrote:
|>     try:
|>         useappropriately(thefile)
|>     except ItWasWrong, howwasitwrong:
|>         dealwithwrongness()
|
| My problem with this approach:
|
| (cue dramatic music)
| Our chief error is an IOError...IOError and OSError... Our two errors 
| are IOErrors and OSErrors...and RuntimeErrors.... Our *three* errors are 
| IOErrors, OSErrors, and RuntimeErrors...and an occasional 
| MemoryError.... Our *four*...no... *Amongst* our errors....
|
| I have a hard time catching all the appropriate exceptions that a 
| function may throw, especially if useappropriately(thefile) is 
| non-trivial.  Pure EAFP code sometimes ends up looking like this
|
| try:
|      useappropriately(thefile)
| except IOError:
|      dealwithIOError()
| except OSError:
|       dealwithOSError()
| except RandomError:
|       dealwithRandomError....
|
| and you can *still* get bitten if you haven't anticipated all the ways 
| in which things can go wrong.   (And I know about bare excepts... but 
| having bare excepts in your code opens up its own kettle of worms.) If I 
| really need something to work, I usually do both a pre-check (LBYL) as 
| well as a just-in-case try-except, so that the number of places and ways 
| in which the useappropriately() function can go wrong is minimized.

In principle, I'd expect the exception handler to be more efficient
in programmer time, and more reliable.  That assumes that there is
no cost in letting execution run to the point of failure, which
would not always be the case but doesn't seem to be your worry.

It's a shame that IOError and OSError (and socket.error, etc.) were
never integrated in some way.  I was going to suggest that you could
actually catch all, in a blank except, and then inspect the exception
for an 'errno' attribute - but that wouldn't help with socket.error,
even though the kind of socket errors you'd be looking for do come
with an error.

So it does sort of weaken the case for exception handling - you still
have to account for a set of conditions that you can't identify a priori
without inspecting the code you're going to call.  Conceptually similar
conditions (can't open file) are likely to raise different exceptions
depending on the originating module.  You can't assume that the same
error will return a similar exception between one version of python
and another.  You can't assume that different instances of the same
exception will have consistent properties (though this has gotten better
at the cost of version incompatibility.)

I suppose that if neither strategy is perfect, that leaves us depending
on your judgement.

	Donn Cave, donn at u.washington.edu




More information about the Python-list mailing list