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