Error Handling
If any of the socket functions fail then python throws an exception called socket.error which must be caught.
#handling errors in python socket programs
importsocket  #for sockets
import sys  #for exit
try:
#create an AF_INET, STREAM socket (TCP)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
print 'Failed to create socket. Error code: ' + str(msg[0]) +' , Error message : ' + msg[1]
sys.exit();
print 'Socket Created'
All errors raise exceptions. The normal exceptions for invalid argument types and out-of-memory conditions can be raised; errors related to socket or address semantics raise the errorsocket.error.
Non-blocking mode is supported throughsetblocking(). A generalization of this based on timeouts is supported throughsettimeout().
The modulesocketexports the following constants and functions:
exception socket.error
This exception is raised for socket-related errors. The accompanying value is either a string telling what went wrong or a pair(errno,string)representing an error returned by a system call, similar to the value accompanyingos.error. See the moduleerrno, which contains names for the error codes defined by the underlying operating system.
Changed in version 2.6:socket.erroris now a child class ofIOError.
exception socket.herror
This exception is raised for address-related errors, i.e. for functions that use_h_errno_in the C API, includinggethostbyname_ex()andgethostbyaddr().
The accompanying value is a pair(h_errno,string)representing an error returned by a library call.string_represents the description of_h_errno, as returned by thehstrerror()C function.
exceptionsocket.gaierror
This exception is raised for address-related errors, forgetaddrinfo()andgetnameinfo(). The accompanying value is a pair(error,string)representing an error returned by a library call.string_represents the description of_error, as returned by thegai_strerror()C function. The  error_value will match one of the`EAI*`constants defined in this module.
exceptionsocket.timeout
This exception is raised when a timeout occurs on a socket which has had timeouts enabled via a prior call tosettimeout(). The accompanying value is a string whose value is currently always “timed out”.