首页 > 解决方案 > 发生异常时继续循环

问题描述

我希望循环继续进行,即使在第一次迭代时产生异常。这个怎么做?

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

标签: pythonfor-loop

解决方案


您可以使用dict.get(). None如果密钥不存在,它将返回。您还可以在中指定默认值dict.get(key, default_value)

for i in wl:
    a = mydict.get('sdf')
    print(i)

推荐阅读