Continue the loop after an exception used in python

Question:

I am trying to run a loop with try and exception in python. Initially it runs for p=0 and j=1,2 then falls into the exception. the problem is that then I would like the loop to continue for p=1 and j=1,2,2….can you help me thanks! I tried something like this but it’s not working

for p in range(1):
    for j in range(23):
     try:

      b = response_json[0]['countries'][p]['names'][j]['values']
     except:
         break

Answers:

Overall, using exceptions to handle normal flow is a bad pattern. Exceptions are for, well, exceptions.

Looks like you are trying to iterate over an array with missing keys. Instead of trying each key, you could iterate over the collection directly

country_data = response_json[0]['countries']

for country in country_data:
   for name in country['names']:
      b = name['values']
Answered By: Eriks Klotins

Replace break with continue (or pass).

break jumps to the end of the loop, continue jumps back to the start to continue with the next iteration. pass is a no-op used when a block is empty.

Answered By: kutschkem
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.