0

I'm trying to write socket error handling (exactly err 111 - Connection Refused) but nothing is happening. Terminal print that Errno 111 occured but it's not doing anything with it:

import errno
try:
    #do something
except socket.error, v:
    errorcode=v[0]
    if errorcode==errno.ECONNREFUSED:
        print "Connection Refused"
    else:
        print("Running Application")

Traceback (most recent call last): File "Test.py", line 20, in s.connect((IP, PORT)) File "/usr/lib/python2.7/socket.py", line 224, in meth return getattr(self._sock,name)(*args) socket.error: [Errno 111] Connection refused

Nothing else printed :/ What am I doing wrong ?

3
  • Hard to say without knowing v. Try debugging v or print v to the console, maybe v[0] is not the error code. Commented Feb 17, 2016 at 23:31
  • There is a conceptual error too: printing an error message does not "handle" the exception in any meaningful sense (although too many tutorials think it does). Whatever code called connect is going to want a socket and so all printing an error message does is push the exception to the caller when it tries to use the socket and has None. Now you've managed to swallow the exception, moved the fatal exception to somewhere else in the code, and handled nothing. Commented Feb 23, 2016 at 13:12
  • I can't reproduce your problem. Please show a complete example we can actually run to see the problem. Commented Feb 23, 2016 at 15:57

1 Answer 1

0

I think you need to use v.args[0] to get the error code.

Sign up to request clarification or add additional context in comments.

1 Comment

It doesn't matter whether you index the exception object or its args attribute. Better would be accessing the errno attribute and give the object a more meaningful name than v.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.