代码之家  ›  专栏  ›  技术社区  ›  user

如果发生错误,继续foreach()循环

  •  1
  • user  · 技术社区  · 14 年前

    我现在有一个listview和一个包含XML文档的文件夹。我使用foreach()循环遍历所有XML文件,并相应地将数据加载到listview中。我的问题是,如果in中有错误(例如:如果其中一个XML文件不完全有效、包含错误等),并且仍然将数据添加到listview中,如何继续foreach()循环?我并没有问如何解析XML或如何将其加载到listview中,我知道如何做,只是没有问如何在发生错误时继续循环。

    7 回复  |  直到 14 年前
        1
  •  6
  •   Cheng Chen    14 年前

    你想要:

    foreach(var xml in xmls)
    {
       try
       {
         //import xml to listview
       }
       catch (SomeException e)
       {
         //deal with the exception here
       }
    }
    
        2
  •  1
  •   Cameron    14 年前

    将循环的内部内容包装在 try ... catch 封锁。

    例如

    foreach (var foo in iterableThing) {
        try {
            DoStuff(foo);
        }
        catch (AppropriateException) {
            // Handle the exception (or ignore it)...
        }
        catch (SomeOtherException) {
            // Handle the exception (or ignore it)...
        }
    }
    
        3
  •  0
  •   Jason Jong    14 年前

    你会吗

    foreach( loop )
    {
       try {
       }
       catch (Exception ex)
       {
          // all errors caught here, but the loop would continue
       }
    }
    
        4
  •  0
  •   Nilesh Gule    14 年前

    您可以在try catch块中执行文件处理并处理错误条件。您可以在catch中优雅地处理错误并继续加载数据。

        5
  •  0
  •   Nelson Miranda    14 年前

    我认为你应该这样做:

    foreach(var doc in docs)
    {
        //Make a function to evaluate the doc
        if(isValid(doc))
        {
            //Logging or something
            continue;
        }
        //Add data to listview
    }
    
        6
  •  0
  •   Ed Power    14 年前

    如果处理代码抛出异常,则使用 try/catch 封锁。如果你用 if 阻止,然后使用 continue .

        7
  •  0
  •   Tomas Petricek    14 年前

    如果您需要更频繁地使用它,或者如果您只想拥有更优雅的代码,则可以使用lambda表达式和委托来为此目的创建新的抽象:

    static void SafeForEach<T>(this IEnumerable<T> source, Action<T> op) {
      foreach(var el in source) {
        try { op(el); }
        catch (Exception e) { }
      }
    }
    

    然后你可以写:

    xmls.SafeForEach(xml => {
         // Xml processing
      });
    

    但是,在预期有错误的情况下使用异常并不是最好的编程风格。如果你能写一个方法,比如 IsValid 如果文档有效,则返回true,然后您可以编写:

    foreach(var xml in xmls.Where(x => x.IsValid)) { 
      // Xml processing
    }