【问题标题】:Continuing for loop when exception occurs [duplicate]发生异常时继续循环[重复]
【发布时间】:2020-08-03 04:49:46
【问题描述】:

我希望循环继续进行,即使在第一次迭代时生成异常。如何做到这一点?

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

【问题讨论】:

  • 在循环体内移动try / except

标签: python for-loop


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 这是不正确的。 print 将被跳过。
    • 这两行代码是独立的,所以你可以把print移到第一位。
    • 另外,使用捕获所有异常的裸except 是不好的做法。仅捕获您知道可能引发的异常。
    【解决方案3】:

    这是我解决问题的方法
    希望它对您有所帮助

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

    【讨论】:

      猜你喜欢
      • 2018-12-30
      • 1970-01-01
      • 2016-07-17
      • 2022-11-04
      • 2013-02-05
      • 1970-01-01
      • 1970-01-01
      • 2020-07-01
      • 2018-03-20
      相关资源
      最近更新 更多