How to catch socket timeout?

Peter Otten __peter__ at web.de
Mon Sep 22 09:52:17 EDT 2003


Achim Domma wrote:

> "Bob Halley" <halley at play-bow.org> wrote in message
> news:mailman.1064178330.17024.python-list at python.org...
>> So, all you need to do is put the socket.timeout except clause before
>> any socket.error clause:
>>
>> try:
>>     self.data = self.page.read()
>> except socket.timeout: ...
>>         except socket.error,e: ...
> 
> Thanks, that works fine, but I don't understand why the exception was not
> catched in my case. If I write it like this
> 
> try:
>     self.data = self.page.read()
> except socket.error,e: ...
> except socket.timeout: ...
> 
> the exception should be catched by the socket.error handler. Or am I
> wrong? In my case it was not catched at all. Very mysterious from my point
> of view, but it works now.
> 
> Achim

Achim, both you and me got it wrong the first time. The important part is to
put both urlopen() and page.read() into the try clause, as Alan Kennedy has
already shown. Both statements can throw a timeout exception, so it's sheer
luck that it worked this time. 
And yes, if you put

except socket.error:

before

except socket.timeout:

the latter will never be executed. General structure:


from urllib2 import urlopen
import socket

slowurl = "http://127.0.0.1/timeout?delay=100"
socket.setdefaulttimeout(1)

try:
    data = urlopen(slowurl)
    data.read()
except socket.timeout: 
    print "Timeout raised and caught"

Peter





More information about the Python-list mailing list