Subject: [Tutor] Re: Tutor Testing for response from a Web site
Thu Apr 10 12:47:01 2003
>>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.
># 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()
> print "Server connection could not be made."
> print "Something has gone wrong"
> print sys.exc_info()
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:
print "Begin Downloading..."
metall = urllib.urlopen(metURL).read()
print "Server connection could not be made."
print "Something has gone wrong."
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