我希望循环继续进行,即使在第一次迭代中生成异常。该怎么做?
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
答案 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)