Dan Perl wrote:
"Aggelos I. Orfanakos" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]

Thanks. This should now be OK:

#try:
#    try:
#        s = ... # socket opens
#
#        # various code ...
#    except socket.error, x:
#        # exception handling
#finally:
#    s.close() # socket closes



Why the nested try's? If I understand your intention correctly this should do the same thing:

try:
     s = ... # socket opens
     # various code ...
except socket.error, x:
     # exception handling
s.close() # socket closes

You would need the try-finally statement only if you expect it to handle other exceptions than socket.error or if the socket.error is re-raised in the "except" clause. Otherwise, the try-finally statement is redundant because no socket.error are getting out of the try-except statement.

Dan



i always use the try/finally statement with resources, but in a slightly different way than the above two examples:


s = ... # socket opens
try:
    # various code ...
finally:
    s.close()


or, if i want to handle the socket.error if s gets successfully bound,


s = ... # socket opens try: try: # various code except socket.error e: # exception handling finally: s.close()

i disagree with the statement:

"You would need the try-finally statement only if you expect it to handle other exceptions than socket.error or if the socket.error is re-raised in the "except" clause. Otherwise, the try-finally statement is redundant because no socket.error are getting out of the try-except statement."

IMO, that is not the reason for the try/finally statement and it is not redundant. the try/finally statement guarantees the resource is closed and the try/finally statement only gets executed if and only if the opening of the resource doesn't raise an exception. it has nothing to do with exception handling.

in the previous 2 examples s = ... was placed inside the try/finally, but if an exception occures and s doesn't get bound to an object, then s.close() in both examples will raise a NameError on s.

bryan

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to