异常后继续循环执行

时间:2014-05-21 09:19:55

标签: c# wpf

如果发生异常,我希望for循环继续执行(100个中的99个,对于门户网站来说是连接问题),这意味着转移到连接到下一个门户网站。

我认为使用finally并使用goto,但我不喜欢使用goto

 for (int i = 0; i < Portals.Count; i++)
{
    try
       {
        if (!Portals[i].IsConnected)
          {
             Portals[i].Connect();
             ///..Permorm variours actioms...
          }
        }
    catch 
        {
         Window7 win = new Window7();
         win.label1.Content = "Connect to Portal " + (i + 1).ToString() + " Failed..";
         win.ShowDialog();
         return;
        }

1 个答案:

答案 0 :(得分:2)

如果您希望继续使用try / catch之后放置的代码,请执行以下操作:
(只需删除退货;声明)

for (int i = 0; i < Portals.Count; i++)
{
    try
    {
        if (!Portal[i].IsConnected)
        {
            Portal[i].Connect();
            ///..Permorm variours actioms...
        }
    }
    catch 
    {
        Window7 win = new Window7();
        win.label1.Content = "Connect to Portal " + (i + 1).ToString() + " Failed..";
        win.ShowDialog();
    }
    // TODO - Some more code here
}

如果您希望在发生异常时停止该迭代,只需通过继续替换您的回报:

for (int i = 0; i < Portals.Count; i++)
{
    try
    {
        if (!Portal[i].IsConnected)
        {
            Portal[i].Connect();
            ///..Permorm variours actioms...
        }
    }
    catch 
    {
        Window7 win = new Window7();
        win.label1.Content = "Connect to Portal " + (i + 1).ToString() + " Failed..";
        win.ShowDialog();
        continue;
    }
    // TODO - Some more code here
}