EAFP vs LBYL (was Re: A little disappointed so far)
VanL
vlindberg at verio.net
Mon May 19 09:58:01 EDT 2003
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.
Am I seriously misguided here?
VanL
More information about the Python-list
mailing list