python - socket.settimeout quits program not using except clause -
i have below python code, no data received , program quits without running except clause print , return statements
any ideas on happening?
sock.settimeout(10) try: pkt = sock.recv(255) except socket.error: print "connection timed out!" return
the problem socket.timeout
exception different exception socket.error
. so, except socket.error:
doesn't catch socket.timeout
same reason except valueerror:
doesn't catch keyerror
.
(the documentation isn't obvious in 2.x. 1 of many things cleaned in python 3.3/pep 3151—see the nice new docs—but long you're sticking 2.x don't benefit that.)
the right solution handle right error:
sock.settimeout(10) try: pkt = sock.recv(255) except socket.timeout: print "connection timed out!" return
if want handle socket errors (like, say, failure recv
call) same way:
sock.settimeout(10) try: pkt = sock.recv(255) except (socket.timeout, socket.error) e: print "connection timed out or erred out: {}!".format(e) return
notice added in as e
, added output. way, if unexpected goes wrong, you'll know what went wrong, instead of having guess.
of course, may want handle 2 errors differently, well:
sock.settimeout(10) try: pkt = sock.recv(255) except socket.timeout: print "connection timed out!" return except socket.error e: print "connection erred out: {}!".format(e) return
Comments
Post a Comment