tags:

views:

140

answers:

2

So, simply I want to be able to run a for across a list of URLs, if one fails then I want to continue on to try the next.

I've tried using the following but sadly it throws and exception if the first URL doesn't work.

servers = ('http://www.google.com', 'http://www.stackoverflow.com')
for server in servers:
    try:
        u = urllib2.urlopen(server)
    except urllib2.URLError:
        continue
    else:
        break
else:
    raise

Any ideas?

Thanks in advance.

A: 
servers = ('http://www.google.com', 'http://www.stackoverflow.com')
for server in servers:
    try:
        u = urllib2.urlopen(server)
    except urllib2.URLError:
        continue
    else:
        break
else:
    raise

This code breaks out of the loop if the url connection doesn't raise an error (else: break part).

Do you want the 2nd one used only if the first fails?

edit: I thought that the else: following the for loop should raise because of the break, but in my quick test that didn't work ... because my understanding of for/else was wrong

pycruft
The for should only continue if the first url does cause an exception, this should be the case for any number of URLS in the list.E.g. if 1 and 2 fail then the third should be tried.
Kura
A: 

So the problem turned out to be user error. I was trying stupid domains like "wegwegwe.com" but I never actually had a usable domain in the list, so eventually it did just raise the exception.

User error.

Kura