46

How could I catch socket.error: [Errno 111] Connection refused exception ?

try:
    senderSocket.send("Hello")
except ?????:
    print "catch !"     
URL87
  • 10,667
  • 35
  • 107
  • 174

1 Answers1

86

By catching all socket.error exceptions, and re-raising it if the errno attribute is not equal to 111. Or, better yet, use the errno.ECONNREFUSED constant instead:

import errno
from socket import error as socket_error

try:
    senderSocket.send('Hello')
except socket_error as serr:
    if serr.errno != errno.ECONNREFUSED:
        # Not the error we are looking for, re-raise
        raise serr
    # connection refused
    # handle here
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 1
    Now when it caught it propts `AttributeError: type object '_socketobject' has no attribute 'error'` ... I using `Python 2.6.5` . – URL87 Jan 20 '13 at 14:32
  • 1
    @URL87: Did you do `from socket import socket`? Don't mask the module name with a different object in your code. – Martijn Pieters Jan 20 '13 at 15:10
  • @URL87: you can also do `from socket import error` then `except error, serr:` but that is not as readable. Updated the answer to use a middle ground. – Martijn Pieters Jan 20 '13 at 15:15
  • 8
    FYI, If using Python 3.3 it now has `ConnectionRefusedError` and `socket.error` is deprecated. – Mark Tolonen Jan 20 '13 at 18:05
  • `serr.errno` probably only works from python 2.6 onwards, when `socket.error` was made inherit from `IOError`. Prior to that, `serr.args[0]` seems to do the same. – Andre Holzner Mar 11 '15 at 13:24