如何继续尝试和捕获foreach?

时间:2012-10-07 03:08:47

标签: c# .net

如果我在执行foreach期间捕获异常,我可以继续执行吗?

foreach (string d in Directory.GetDirectories(path))
    {
        try
        {
            foreach (string f in Directory.GetFiles(path))
            {
                //do something
            }
            //do something
        }
        catch
        {
           // If there is an error in the foreach, I want it to keep on going
        }
    }

我问这是因为它在foreach获取所有文件之前突然终止。

3 个答案:

答案 0 :(得分:9)

简单地说:

foreach (string d in Directory.GetDirectories(path))
{
        foreach (string f in Directory.GetFiles(path))
        {
            try
            {
                //do some thing
            }
            catch
            {
               // If there is an error on the foreach, I want it to keep on going to search another one
            }
        }
        //do some thing
}

答案 1 :(得分:2)

foreach (string d in Directory.GetDirectories(path)) {
    foreach (string f in Directory.GetFiles(path)) {
        try {
            //do some thing
        } catch { /* log an error */ }
    }

    try {
        //do some thing
    } catch { /* log an error */ }
}

答案 2 :(得分:-2)

foreach (string d in Directory.GetDirectories(path))
{
    try
    {
        foreach (string f in Directory.GetFiles(path))
        {
            //do something
        }
        //do something
    }
    catch(Excepion)
    {
       // If there is an error in the foreach, log error and...
            continue;
    }
}