title: Python socket connection exception
body: <p>I have a socket-connection going on and I wanna improve the exception handling and I'm stuck. Whenever I call <code>socket.connect(server_address)</code> with an invalid argument the program stops, but doesn't seem to raise an exception. Here is my code:</p>
  <pre><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 &quot;Couldnt connect with the socket-server: %s\n terminating program&quot; % msg
              sys.exit(1)
      
      def initiate(self):
          self.sock.send(&quot;start_logging&quot;)
      
      def log(self):
          self.logging  = True  
          buf = self.sock.recv(6000)
          if len(buf)&gt;0:
              nbuf = buf[len(buf)-12:len(buf)]
              self.x, self.y, self.z = struct.unpack(&quot;&lt;iii&quot;, nbuf) 
      
      def stop_logging(self):
          print &quot;Stopping logging&quot;
          self.logging = False
          self.sock.close()
              
  </code></pre>
  <p>The class maybe looks a bit wierd but its used for receiving coordinates from another computer running ARToolKit. Anyway, the issue is at the function <code>connect()</code>:</p>
  <pre><code>def connect(self,server_address):
      try:
          self.sock.connect(server_address)
      except socket.error, msg:
          print &quot;Couldnt connect with the socket-server: %s\n terminating program&quot; % msg
          sys.exit(1)
  </code></pre>
  <p>If I call that function with a random IP-address and portnumber the whole program just stops up at the line:</p>
  <pre><code>self.sock.connect(server_address)
  </code></pre>
  <p>The documentation I've read states that in case of an error it will throw a socket.error-exception. I've also tried with just:</p>
  <pre><code>except Exception, msg:
  </code></pre>
  <p>This, if I'm not mistaken, will catch any exceptions, and still it yields no result. I would be very grateful for a helping hand. Also, is it okay to exit programs using sys.exit when an unwanted exception occurs?</p>
  <p>Thank you</p>