Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: trying to raise multi-purpose exception for multiple error types

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)

like image 259
ffledgling Avatar asked Jul 28 '12 00:07

ffledgling


People also ask

Can you have multiple excepts for one try in Python?

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?

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.

How do you raise error type exception in Python?

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.


2 Answers

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.

like image 162
SilverbackNet Avatar answered Oct 13 '22 20:10

SilverbackNet


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.

like image 39
cababunga Avatar answered Oct 13 '22 18:10

cababunga