secatt
secatt

Reputation: 43

How to handle error in a for loop (python) and continue execution

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

Upvotes: 1

Views: 59

Answers (3)

bigbounty
bigbounty

Reputation: 17408

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())

Upvotes: 0

CircuitSacul
CircuitSacul

Reputation: 1850

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

Upvotes: 2

Chems Eddine
Chems Eddine

Reputation: 153

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

Upvotes: 2

Related Questions