Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get back to the for loop after exception handling

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?

like image 965
Zeynel Avatar asked Dec 03 '09 22:12

Zeynel


People also ask

How do you continue a loop after catching exception in try catch?

As you are saying that you are using try catch within a for each scope and you wants to continue your loop even any exception will occur. So if you are still using the try catch within the loop scope it will always run that even exception will occur. it is upto you how you deal with exception in your way.

How do you continue running after an exception in Python?

Perhaps after the first for-loop, add the try/except . Then if an error is raised, it will continue with the next file. This is a perfect example of why you should use a with statement here to open files. When you open the file using open() , but an error is catched, the file will remain open forever.

How do you retry a loop in Python?

Do a while True inside your for loop, put your try code inside, and break from that while loop only when your code succeeds.


2 Answers

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.

like image 143
Mark Byers Avatar answered Sep 19 '22 21:09

Mark Byers


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" 
like image 22
Jochen Ritzel Avatar answered Sep 17 '22 21:09

Jochen Ritzel