Subject: [Tutor] Re: Tutor Testing for response from a Web site
Jeff Shannon
jeff@ccvcorp.com
Thu Apr 10 14:51:01 2003
Anna Ravenscroft wrote:
>On Thursday 10 April 2003 11:48, Jeff Shannon wrote:
>
>>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?
>
>
>[...]
>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.
>
Yes, exactly. The 'finally' clause will always execute, no matter how
the 'try' block is exited (whether by exception, by return, by
sys.exit(), or by simply reaching the end and continuing). The only
thing that will stop a 'finally' clause from executing is a complete
crash of the Python interpreter, which almost never happens unless
there's a problem in an extension module. (Or if the interpreter is
killed from outside, as might be necessary if it's caught in an infinite
loop or a deadlock while inside the try block.)
This makes a 'finally' clause an ideal way to make sure that cleanup
always happens.
Jeff Shannon
Technician/Programmer
Credit International