views:

159

answers:

3

Hello,

I am ready to run this code but before I want to fix the exception handling:

for l in bios:
    OpenThisLink = url + l
    try:
        response = urllib2.urlopen(OpenThisLink)
    except urllib2.HTTPError:
        pass
    bio = response.read()
    item = re.search('(JD)(.*?)(\d+)', bio)
    ....

As suggested here, I added the try...except but now if a page doesn't open I get this error:

bio = response.read()
NameError: name 'response' is not defined

So the program continues to execute. Instead I want it to go back to the for loop and try the next url. I tried break instead of pass but that ends the program. Any suggestions?

+7  A: 

Use continue instead of break.

The statement pass is a no-op (meaning that it doesn't do anything). The program just continues to the next statement, which is why you get an error.

break exits the loops and continues running from the next statement immediately after the loop. In this case, there are no more statements, which is why your program terminates.

continue restarts the loop but with the next item. This is exactly what you want.

Mark Byers
After an exception is handled it returns to where it was caught, just like most burglers.
jathanism
thanks. `continue` works fine.
Zeynel
+1  A: 

Try is actually way more powerful than that. You can use the else block here too:

try:
    stuff
except Exception:
    print "oh no a exception"
else:
    print "oh yay no exception"
finally:
    print "leaving the try block"
THC4k
A: 

you are getting that error because when the exception is thrown the response variable doesn't exist. If you want to leave the code how you have it you will need to check that response exists before calling read

if response:
    bio = response.read()
    ...

having said that I agree with Mark that continue is a better suggestion than pass

John Stallings