KKa
KKa

Reputation: 408

urlopen() and read() [urllib2]

I am testing for some exception handling and would want to know, which network related errors could occur in the following code:

candidate =  urllib2.urlopen() #1
candidate.read() #2

I know that #1 causes URLError. Are there any other errors that could be raised? In particular does #2 require network connection?

Upvotes: 0

Views: 554

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121904

Reading requires that the socket is still open; although some response data will be buffered generally you pull data down by reading. The candidate.read() call will block until the whole response has been read.

As such socket.error (a subclass of IOError) can be raised even during the candidate.read() call.

Apart from the urllib2.URLError exception (plus subclass), urllib2.urlopen() can also raise httplib.HTTPException with various subclasses, socket.error, or when fed invalid data (illegal URL string, etc.), ValueError. Once you have a response object, response.read() can also raise socket.error and httplib.HTTPException.

httplib.HTTPException is a straight Exception subclass. socket.error and urllib2.URLError are IOError subclasses.

Upvotes: 3

Related Questions