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
python exception exception-handling sockets
erling
source share