"Try:" which only encompasses head of compound statement

Lawrence D'Oliveiro ldo at geek-central.gen.new_zealand
Tue Aug 28 07:05:01 CEST 2007

In message <1188256903.075011.173820 at k79g2000hse.googlegroups.com>, Carl
Banks wrote:

> Consider this: is there any other code in your program that has to do
> something different based on whether you successfully opened this file
> or not?  If so, how will you notify it whether the call has succeeded
> or not?  Very often, the caller itself needs to know.  You could, say,
> set a flag to indicate it's failed, but why do that when you could
> simply let the caller detect and handle the error itself?

I am generally wary of exceptions, and like to contain them as much as
possible. So my answer to your point is something like

    try :
        f = open(TheFile, "r")
    except IOError, (ErrNo, Msg) :
        if ErrNo != errno.ENOENT :
        #end if
        f = None
    #end try

(Note how I check for the specific error code I want to handle.) Then later
on I can determine if the file was successfully opened by

    if f != None :
        ... further processing on f ...
    #end if

More information about the Python-list mailing list