"Try:" which only encompasses head of compound statement

Scott David Daniels daniels at dsl-only.net
Tue Aug 28 00:14:59 EDT 2007


Ben Finney wrote:
> Jameson.Quinn at gmail.com writes:
> ... try to only catch exceptions from the
> minimum amount of code that does one discrete action.
> 
>     try:
>         input_file = open(my_filename)
>     except IOError, exc:
>         print "Can't open myfile: %(exc)" % locals()
> 
>     for line in input_file:
>         count += open_and_process_subfile(line)
Actually, this will be followed by some foolishness because
(1) print "Can't open myfile: %(exc)" % locals()
     Should at least be:
         print "Can't open myfile: %(exc)s" % locals()
     But more reasonably:
         print "Can't open myfile: %s" % exc
and
(2) Even if the print succeeds, the code will fall through into the loop 
and you'll (if you are lucky) get a complaint about
     NameError: name 'input_file' is not defined
You'd need to "raise" after the print, but the normal IOError failure
to open message already includes the name of the file it tried to get
to in an attribute "filename", so just catch it outside this code (as
others have already suggested).

-Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list