When to use try and except?

Cameron Laird claird at lairds.us
Sat Aug 30 09:29:27 EDT 2008


In article <00c7058c-2b26-42bf-8f5b-2bebe31b2130 at k7g2000hsd.googlegroups.com>,
Carl Banks  <pavlovevidence at gmail.com> wrote:
			.
			.
			.
>> Basically, there's a general principle (EAFP: Easier to ask
>> forgiveness than permission) in Python to just "try" something and
>> then catch the exception if something goes wrong. This is in contrast
>> to e.g. C where you're supposed to "Look before you leap" (LBYL) and
>> check for possible error conditions before performing the operation.
>
>I wouldn't say that the possibility of EAFP in Python makes it
>obsolute to use LBYL.  (Error checking seems to be too broad a subject
>to apply the One Obvious Way maxim to.)  C isn't always LBYL anyway;
>sometimes it's DFTCFE "Don't forget to check for errors".
>
>I tend to use EAFP to check if something "wrong" happened (a missing
>file, invalid input, etc.), and LBYL for expected conditions that can
>occur with valid input, even when that condition could be tested with
>a try...except.  For instance, I'd write something like this:
			.
			.
			.
I'll reinforce what Carl tells:  a wise developer knows how to
work in different styles in different circumstances.  In a retail
C program, for example, it might be wisest to emphasize ahead-of-
time diagnostics such as, "the configuration file ... is {missing,
inaccessible,locked, ...}", while a system-level library making
what apparently is the same call needs to check return values
carefully, to guard against the possibility that the system's
state has changed while executing consecutive statements.



More information about the Python-list mailing list