简体   繁体   English

异常后继续循环执行

[英]continue for loop execution after exception

I want the for loop to continue execution if an exception occurs (99 out of 100, wiil be conection problem to portal), meaning move to connecting to next portal. 如果发生异常,我希望for循环继续执行(100个中的99个,对于门户网站来说是连接问题),这意味着转移到连接到下一个门户网站。

I thought using I finally compined with a goto but I dislike using goto . 我以为使用我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;
        }

If you wish to continue with the code placed after the try/catch use this : 如果您希望继续使用try / catch之后放置的代码:
(simply remove the return; statement) (只需删除return;语句)

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
}

If you wish to stop that iteration if an Exception occurs, simply replace your return by a continue : 如果您希望在发生异常时停止该迭代,只需用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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM