0

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

1
  • 1
    Please provide a minimal reproducible example. The expected behavior and difference from the provided code is hard to understand. Commented Oct 27, 2022 at 7:10

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

why do you need continue, once you catch the exception, it will go to next iteration anyway
@Epsi95 - I think the commented parts shouldn't be executed, so continue is necessary. But the question is hardly understandable.
yes, then, they should be put in try block, I think.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.