异常后继续循环执行

本文关键字:执行 循环 继续 异常 | 更新日期: 2023-09-27 18:04:28

我希望for循环在发生异常时继续执行(99/100,将是连接到门户的问题),这意味着移动到连接到下一个门户。

我认为使用I finallygoto结合,但我不喜欢使用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;
        }

异常后继续循环执行

如果您希望继续执行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
}

如果您希望在发生Exception时停止迭代,只需将return替换为continue:
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
}