Home > Software engineering >  Continue the loop after an exception used in python
Continue the loop after an exception used in python

Time:01-13

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

CodePudding user response:

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']

CodePudding user response:

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.

  • Related