Regarding exception handling

Dan Perl danperl at rogers.com
Mon Jan 31 01:19:25 EST 2005


"Aggelos I. Orfanakos" <aorfanakos at gmail.com> wrote in message 
news:1107140290.363099.273690 at c13g2000cwb.googlegroups.com...
> Good point, but with your way, if "s = ... # socket opens" fails, then
> nothing will catch it. What I usually do is what I wrote above (place
> it below the 2nd try), and when attempting to close it, first use an if
> like: "if locals().has_key('s'):".

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

This handles all the socket exceptions in one shot.  The only problem is 
that different problems may have to be handled differently.  For instance, 
you may need to handle a transmission that failed in the middle differently 
than a failure to open the socket.

Dan





More information about the Python-list mailing list