Subject: [Tutor] Re: Tutor Testing for response from a Web site
Anna Ravenscroft
revanna@mn.rr.com
Thu Apr 10 13:39:01 2003
On Thursday 10 April 2003 11:48, Jeff Shannon wrote:
> charlie@begeistert.org wrote:
> >>3) Can this code be written so that I only need to have ONE
> >> f_object.close() statement if any exception occurs? As it stands
> >> now, I have to repeat it for each exception.
> >
> >Yes, you just add a finally: f_object.close() at the end.
>
> [...]
>
> >try:
> ># print "\nBEGIN DOWNLOADING ETA (MET) MOS"
> > print "BEGIN DOWNLOADING ETA (MET) MOS"
> ># this is Python so we don't need more \n than absolutely necessary
> > metall = urllib.urlopen(metURL).read()
> > f_object.write(metall)
> >except IOError:
> > print "Server connection could not be made."
> >except:
> > print "Something has gone wrong"
> > print sys.exc_info()
> >finally:
> > f_object.close()
>
> This actually doesn't *quite* work. You can't have an 'except:' clause
> and a 'finally:' clause hanging off the same 'try:'. You need to nest
> them:
>
> try:
> try:
> print "Begin Downloading..."
> metall = urllib.urlopen(metURL).read()
> f_object.write(metall)
> except IOError:
> print "Server connection could not be made."
> except:
> print "Something has gone wrong."
> print sys.exc_info()
> finally:
> f_object.close()
Just to make sure *I'm* understanding things here... this 'finally' will
*always* execute regardless of whether there were any exceptions. Right?
> In this particular case, you don't really even need the 'finally',
> because any possible exception is already being caught, so execution
> will always continue. That might not be a good idea, though -- if
> you're getting no connection, or if you're having other unspecified
> errors, it might be best to go ahead and terminate the program, or
> perhaps return from the function this is in and try it again in ten
> minutes... In those cases, you could add a 'sys.exit(1)' or a
> 'return' to each except clause, the 'finally' will ensure that f_object
> gets closed, and a successful download will leave execution continuing
> just after the 'finally' while an exception would end execution (within
> this scope).
So, f_object gets closed whether download was successful or not, as a
"clean-up" action after the download has been attempted. Yes?
Just trying to make sure I understand.
Anna