Move socket.close() into finally block