Reputation: 309
I'm having the following code:
try:
while 1:
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.settimeout(5);
s.connect((HOST,PORT))
print("before send")
#time.sleep(10);
#s.sendall('GET / HTTP/1.1\r\nConnection: Keep-Alive\r\nHost: www.google.lt\r\n\r\n')
data=s.recv(52)
print("after send");
s.close()
if string.find(data,"HTTP/1.1 200 OK") == -1:
print("Lost Connection")
print(data)
time.sleep(2)
except KeyboardInterrupt:
print("CTRL C occured")
except socket.error:
print("socket error occured: ")
except socket.timeout:
print("timeout error")
I have commented the sendall function to test how recv generates timeout exception. But the problem is that i get socket.error exception. If i change the last lines of code to:
except socket.timeout:
print("timeout error")
except socket.error:
print("socket error occured: ")
Then i get socket.timeout exception. So what exception is really generated?
Upvotes: 7
Views: 14671
Reputation: 62948
socket.timeout
is a subclass of socket.error
. Really it's socket.timeout
. When you catch a socket.error
first, you catch a more general case.
>>> issubclass(socket.timeout, socket.error)
True
This code is correct:
except socket.timeout:
print("timeout error")
except socket.error:
print("socket error occured: ")
Try to catch specifically socket.timeout
, then other socket.error
s.
Upvotes: 20