I'm working with urllib and urllib2 in python and am using them to retrieve images from urls.
Using something similar to :
try: buffer=urllib2.url_open(urllib2.Request(url)) f.write(buffer) f.close except (Errors that could occur): #Network Errors(?) print "Failed to retrieve "+url pass
Now what happens often is that the image does not load/is broken when using the site via a normal web browser this is presumably because of high server load or because the image does not exist or could not be retrieved by the server.
Whatever the reason may be, the image does not load and a similar situation can also/is likely to occur when using the script. Since I do not know what error it might it throw up how do I handle it?
I think mentioning all possible errors in the urllib2,urllib library in the except statement might be overkill so I need a better way.
(I also might need to/have to handle broken Wi-Fi, unreachable server and the like at times so more errors)
According to the Python Documentation: A try statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. In this example, we have two except clauses.
Why is it best practice to have multiple except statements with each type of error labeled correctly? Ensure the error is caught so the program will terminate In order to know what type of error was thrown and the.
As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.
There are only two exceptions you'll see, HTTPError (HTTP status codes) and URLError (everything that can go wrong), so it's not like it's overkill handling both of them. You can even just catch URLError if you don't care about status codes, since HTTPError is a subclass of it.
If you just want to print explanation of what happened, just print the exception itself.
except Exception, e:
print e
Exception object's str() method will retrieve human readable message for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With