6

如果我在执行 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获取所有文件之前突然终止。

4

3 回答 3

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
}
于 2012-10-07T03:12:05.170 回答
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 */ }
}
于 2012-10-07T03:11:21.933 回答
0
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;
    }
}
于 2014-02-27T17:57:37.457 回答