什么时候抛出异常会打破for循环?

时间:2015-06-15 11:01:58

标签: c# oop exception

如果在完成循环之前抛出异常,DoSomething中的for循环是否会中断。

var test = new Test(...)

try{
      //do something in test
      test.DoSomething()
  }
  catch(myException e)
  {
     \\do something about this exception
  }



class Test
{
   public void DoSomething(...)
   {
         for(var i=0;i < 5; i++)
         {
                ...

                if(some smoke)
                  {
                      throw new myException {...}
                  }

                ...
          }
}

3 个答案:

答案 0 :(得分:1)

打破

public void DoSth()
{
    try
    {
        for(int i = 0; i ... ; i++)
        {
            if(...)
            {
                throw new Exception();
            }
        }
    }
    catch 
    {

    }
}

不打破

public void DoSth()
{
    for(int i = 0; i ... ; i++)
    {
        try
        {
            if(...)
            {
                throw new Exception();
            }
        }
        catch
        {
        }

    }
}

因为当你遇到异常时,你会跳进catch块。并且当catch块在for中时它不会破坏for。 因为在i的下一次迭代中你仍然在for。

答案 1 :(得分:1)

您可以通过定义循环来测试您的问题,看看您是否可以在异常后到达某个点:

void Main()
{
    try{
        DoSomething();
    }
    catch{
        Console.WriteLine("Yup. Breaks");
    }
}
void DoSomething()
{
    for(int i = 0; i <= 1; i++)
    {
        if(i == 0) {
            throw new NotImplementedException();
        }
        if( i != 0)
        {
            Console.WriteLine("Loop continues");
        }
    }
}

并回答你的问题:不,代码中断了,因为异常本身没有得到处理。

如果在循环中放置了try / catch块,则可以在正确处理异常后在catch块中调用continue;以继续迭代。

答案 2 :(得分:0)

来自How to: Handle Exceptions in Parrallel loops

  

Parallel.For和Parallel.ForEach重载没有任何特殊机制来处理可能抛出的异常。在这方面,它们类似于常规for和foreach循环(For Basic中的For和For Each);未处理的异常会导致循环立即终止。

通过抛出一个新的myException(...),你的循环中有一个未处理的异常,所以你的循环会中断,你的异常会抛到它上面的catch中