簡體   English   中英

異常后繼續循環執行

[英]continue for loop execution after exception

如果發生異常,我希望for循環繼續執行(100個中的99個,對於門戶網站來說是連接問題),這意味着轉移到連接到下一個門戶網站。

我以為使用我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之后放置的代碼:
(只需刪除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
}

如果您希望在發生異常時停止該迭代,只需用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