发生异常时继续循环

时间:2020-08-03 04:49:46

标签: python for-loop

我希望循环继续进行,即使在第一次迭代中生成异常。该怎么做?

mydict = {}
wl = ["test", "test1", "test2"]
    
try:
  for i in wl:
   a = mydict['sdf']
   print(i)
            
except:
       # I want the loop to continue and print all elements of list, instead of exiting it after exception
       # exception will occur because mydict doesn't have 'sdf' key
    pass

3 个答案:

答案 0 :(得分:1)

您可以使用dict.get()。如果密钥不存在,它将返回None。您也可以在dict.get(key, default_value)

中指定默认值
for i in wl:
    a = mydict.get('sdf')
    print(i)

答案 1 :(得分:0)

我能建议的最好方法是将try移入循环,如下所示:

mydict = {}
wl = ["test", "test1", "test2"]
for i in wl:
    try:
        a = mydict['sdf']
        print(i)

    except:
        continue

答案 2 :(得分:0)

这是我为您解决问题的方法
希望它为您服务

mydict = {}
wl = ["test", "test1", "test2"]

for i in wl:
    try:
        a = mydict['sdf']
    except:
        pass
    print(i)