Python handling specific error codes?

Question:

Hey I’m wondering how to handle specific error codes. For example, [Errno 111] Connection refused

I want to catch this specific error in the socket module and print something.

Asked By: AustinM

||

Answers:

This seems hard to do reliably/portably but perhaps something like:

import socket

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(('localhost', 4167))
except socket.error, e:
    if 'Connection refused' in e:
        print '*** Connection refused ***'

which yields:

$ python socketexception.py 
*** Connection refused ***

Pretty yucky though.

Answered By: Marc Abramowitz

If you want to get the error code, this seems to do the trick;

import errno

try:
    socket_connection()
except socket.error as error:
    if error.errno == errno.ECONNREFUSED:
        print(os.strerror(error.errno))
    else:
        raise

You can look up errno error codes.

Answered By: Utku Zihnioglu

On Unix platforms, at least, you can do the following.

import socket, errno
try:
    # Do something...
except socket.error as e:
    if e.errno == errno.ECONNREFUSED:
        # Handle the exception...
    else:
        raise

Before Python 2.6, use e.args[ 0 ] instead of e.errno.

Answered By: jchl

I’m developing on Windows and found myself in the same predicament. But the error message always contains the error number. Using that information I just convert the exception to a string str(Exception), convert the error code I wanna check for to a string str(socket.errno.ERRORX) and check if the error code is in the exception.

Example for a connection reset exception:

except Exception as errorMessage:
    if str(socket.errno.ECONNRESET) in str(errorMessage):
        print("Connection reset")
        #etc...

This avoids locale specific solutions but is still not platform independent unfortunately.

Answered By: Edward Severinsen