-1

I am new to Python and facing some issues with exception handling.

When I create a socket and connect it to an IP/port, I want to handle the socket exceptions and not display Python errors on console. I did that with the help of try and except.

try:
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.connect((self.host, self.port))
    except error:
        print 'Socket Error'

But I still get the error printed on console

error: uncaptured python exception, closing channel <SClient 20.0.0.1:5000 at 0x7fe94e0e2e18> (<class 'socket.error'>:[Errno 111] Connection refused [/usr/lib/python2.7/asyncore.py|read|83] [/usr/lib/python2.7/asyncore.py|handle_read_event|446] [/usr/lib/python2.7/asyncore.py|handle_connect_event|454])

Please advice

crazy_coder
  • 1,039
  • 2
  • 8
  • 18
  • `except error` should give you an error about error not being defined ... try just `except:` its frowned upon but should work – Joran Beasley Mar 29 '16 at 22:18
  • I tried except: too. But it still shows the error. – crazy_coder Mar 29 '16 at 23:37
  • First of all, your except clause must be aligned with the try. You haven't identified what the error is. So, run the code without the try, and when it fails, take note of the error that was raised, then put back the try and except with the actual error type – joel goldstick Mar 29 '16 at 23:40
  • After removing try, I get the error as raise socket.error(err, errno.errorcode[err]). Should I now use try and except socket.error? – crazy_coder Mar 30 '16 at 00:01

1 Answers1

0
try:
    a == b
except Exception as e:
    print "error: %s"%(e)

Use this format.

Leviathan
  • 32
  • 5