异常时继续执行while循环

时间:2014-02-12 06:55:07

标签: c#

为什么在发生异常时此代码会继续显示消息? 这意味着我希望完成所有迭代,即使在任何一个迭代中都有任何异常。

  private void cmd_Click(object sender, EventArgs e)
    {
        int i = 0;

        while (i < 10)
        {
            try
            {
                int b = 10/i;
                MessageBox.Show(b.ToString());
                i++;
            } 
            catch (Exception ex)
            {
                continue;
            }
        }      
    }

1 个答案:

答案 0 :(得分:5)

  

此代码在发生异常时继续显示消息

i++;移出try-catch块。当你收到异常

时,你不会增加它
while (i < 10)
{
    try
    {
        int b = 10 / i;
        MessageBox.Show(b.ToString());
    }
    catch (Exception ex)
    {
    }
    i++;
}