Python socket connection exception

I have a socket connection and I want to improve exception handling and I'm stuck. Whenever I use the socket.connect (server_address) function with an invalid argument, the program stops, but does not seem to throw any exceptions. Heres my code

import socket import sys import struct class ARToolkit(): def __init__(self): self.x = 0 self.y = 0 self.z = 0 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.logging = False def connect(self,server_address): try: self.sock.connect(server_address) except socket.error, msg: print "Couldnt connect with the socket-server: %s\n terminating program" % msg sys.exit(1) def initiate(self): self.sock.send("start_logging") def log(self): self.logging = True buf = self.sock.recv(6000) if len(buf)>0: nbuf = buf[len(buf)-12:len(buf)] self.x, self.y, self.z = struct.unpack("<iii", nbuf) def stop_logging(self): print "Stopping logging" self.logging = False self.sock.close() 

The class may look a little strange, but it is used to get coordinates from another computer running ARToolKit. In any case, the problem is with the connect() function:

 def connect(self,server_address): try: self.sock.connect(server_address) except socket.error, msg: print "Couldnt connect with the socket-server: %s\n terminating program" % msg sys.exit(1) 

If I call this function with a random IP address and port number, the whole program simply stops at a line:

 self.sock.connect(server_address) 

The documentation I read indicates that in case of an error, it will throw a socket.error exception. I also tried just:

 except Exception, msg: 

This, if I'm not mistaken, will catch some exceptions, but still will not give a result. I would be very grateful for the help. Also, is it okay to exit the program using sys.exit when an unwanted exception occurs?

thanks

+8
python exception exception-handling sockets
source share
2 answers

If you select a random but valid IP address and port, socket.connect() will try to establish a connection with this endpoint. By default, if no explicit timeout is set for the socket, it will block at the same time and, ultimately, timeout, raising the exception socket.error: [Errno 110] Connection timed out .

The default timeout on my machine is 120 seconds. Perhaps you do not wait too long for socket.connect() (or timeout) to return?

You can reduce the wait time as follows:

 import socket s = socket.socket() s.settimeout(5) # 5 seconds try: s.connect(('123.123.123.123', 12345)) # "random" IP address and port except socket.error, exc: print "Caught exception socket.error : %s" % exc 

Note that if the timeout is explicitly set for the socket, the exception will be socket.timeout , which is derived from socket.error and therefore will be caught by the above exception.

+11
source share

The problem with your last general exception is colon placement. This should be after the entire exception, and not after the except statement. Thus, to catch all exceptions, you will need to:

 except Exception,msg: 

However, from Python 2.6+ you should use the as operator instead of a comma, for example:

 except Exception as msg: 

I managed to run the code in order (note that you need to add a tuple to the connect method). If you want to specifically catch only socket errors, you will need to exclude the socket.error class. Like you:

 except socket.error as msg: 

If you want to make sure that a tuple is entered, just add another exception loop:

 except socket.error as msg: print "Socket Error: %s" % msg except TypeError as msg: print "Type Error: %s" % msg 
+4
source share

All Articles