处理异常 - 捕获后返回错误

时间:2012-12-04 11:49:29

标签: c# .net exception

我想以特定方式处理异常。

try
{
    for (int i = 0; i < rows.Count; i++)
    {
        doSomething();
    }
}
catch (Exception e)
{
    return false;
}

即时运行抛出ienum并尝试使用doSomething()方法找到一个元素。 问题是这个方法在他找不到它时引发异常,但我需要确保我找不到整个枚举中的元素。

所以这就是......我想知道是否有一种方法可以做到这一点:

if(i<rows.Count)
  continueFor;
提前Ty。

2 个答案:

答案 0 :(得分:3)

将try catch放入for循环

for (int i = 0; i < rows.Count; i++)
 {
    try{
      doSomething();
     }
     catch(Exception ex){

        // do something else

     }
 }

这样你可以参考我。或者将一个属性设置为i,然后在你的catch中你将知道(i)是什么。

Int32 lastNumber = 0;

try{
for (int i = 0; i < rows.Count; i++)
 {
     lastNumber = i;
      doSomething();


 } 
}
catch(Exception ex){

        // do something else with lastNumber

}

答案 1 :(得分:0)

您应该从DoSomething方法返回一个布尔值,并测试循环内返回的值。如果你真的需要一个try / catch块,请把它放在方法中,特别是因为你没有使用catch中引发的异常。

 bool returnValue;
 for (int i = 0; i < rows.Count; i++)
                {
                    if(doSomething())
                        returnValue = true;
                }
 return returnValue;