Catch "socket.error: [Errno 111] Connection refused" exception

Question:

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

try:
    senderSocket.send("Hello")
except ?????:
    print "catch !"     
Asked By: URL87

||

Answers:

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
Answered By: Martijn Pieters
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.