如何在for循环中处理错误并继续执行(python)

问题描述 投票:0回答:1

我试图让我的脚本仍然打印行动2 "打印(list1[3]) "和跳过行动1 "打印(list1[9])",如果它不能执行它。我aplozise在advnace,如果我的问题是不够清楚,我试图做我最好的解释的问题。我是一个初学者。

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

try:
  for i in list1:
    #action 1
    print (list1[9])
    #action 2
    print (list1[3])
    break
except:
  pass
python
1个回答
2
投票

试试这个更干净的方式

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

2
投票

只需为每个动作加一个try,而不是两个动作一起加,就像这样。

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

0
投票

除了在循环内使用try

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())
© www.soinside.com 2019 - 2024. All rights reserved.