1

I m trying to get my script to still print action 2 "print (list1[3])" and skip action 1 "print (list1[9])" if it can not execute it. I aplozise in advnace if my question is not clear enough I m trying to do my best to explain the issue. I m a beginner.

list1 = ['a','b','c','d','f']

try:
  for i in list1:
    #action 1
    print (list1[9])
    #action 2
    print (list1[3])
    break
except:
  pass
2
  • 1
    Just wrap the line in question in try/except rather than the whole loop. Commented May 23, 2020 at 2:15
  • @Sushanth the code can not print (print (list1[9])) because the list only contain 5 elements therefore it can not print the 9 element because it does not excite I want to skip that an still print the third one using print (list1[9]. right now my code can not do that. I m trying to fix it. I hope you understand what I mean ? Commented May 23, 2020 at 2:21

3 Answers 3

2

Try this cleaner way

  l = ['a','b','c','d','f']

  # execute the function in try-except
  def try_to_do(fun, index):
     try:
        fun(l[index])
     except:
        pass

  for j in l:
     try_to_do(print, 11)
     try_to_do(print, 1)

  print('Done')
Sign up to request clarification or add additional context in comments.

Comments

2

Just put a try for each action instead of both actions together, like this

list1 = ['a','b','c','d','f']


for i in list1:
  try:
    #action 1
    print (list1[9])
  except IndexError:
    pass
  try:
    #action 2
    print (list1[3])
  except IndexError:
    pass
  break

7 Comments

Wouldn't adding single try..except block enough.. rather than adding to each condition.
@Sushanth Not to solve the problem, because if action1 fails then action2 won't execute
In general, you should try to catch specific errors Since you know you are expecting an IndexError you should catch that specifically with except IndexError:
@MarkMeyer I was focusing on answering his question without adding more detail which would make it harder to understand the answer, but you are correct.
@secatt just replace except: in the above answer with except IndexError: and it will only catch that specific error.
|
0

Use try except inside the loop

list1 = ['a','b','c','d','f']

for i in list1:
    try:
        #action 1
        print (list1[9])
    except:
        print(e.with_traceback())
    try:
        #action 2
        print (list1[3])
    except Exception as e:
        print(e.with_traceback())

1 Comment

@MarkMeyer Changed accordingly

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.