Home > Mobile >  Python if error in a loop continue loop from next iteration
Python if error in a loop continue loop from next iteration

Time:10-27

I have such code:

for i in range(0,5):
  try:
      print(f"opened some_file_{i}")
  except Exception as e:
      print(f"error opening some_file_{i}")
      return
  print(f"i = {i}")

After exception, I need contuinue the loop from the next iteration, but not continue code (print(f"i = {i}")

How can I do it?

I tried to use a break, continue, pass statements and return

CodePudding user response:

Sorry, continue works

for i in range(0,5):
  try:
      print(f"opened some_file_{i}")
  except Exception as e:
      print(f"error opening some_file_{i}")
      continue
  print(f"i = {i}")

So if I had an exception, continue will skip this loop iteration

CodePudding user response:

If you have handled the exception properly it should continue on to the next iteration. You do not require break, continue, pass or return statements. When you try to break or return the control will exit out of the loop/ function. Example:

    for i in range(0,5):
  try:
      print("Hello {}".format(i))
      if i == 3:
          raise Exception("Wrong file path error")
  except Exception as e:
      print(e)

Output

  • Related