如何防止 for 循环在 404 发生时停止?

How to prevent for loop from stopping when a 404 occurs?

我有多个链接,我想在按下开始按钮时处理所有链接。如果其中一个链接 returns 出现 404,我想跳过它并转到下一个。

我当前的代码如下:

try
            {
                foreach (string s in txtInstagramUrls.Lines)
                {
                    if (s.Contains("something"))
                    {
                        using (WebClient wc = new WebClient())
                        {
                            Match m = Regex.Match(wc.DownloadString(s), "(?<=og:image\" content=\")(.*)(?=\" />)", RegexOptions.IgnoreCase);
                            if (m.Success)
                            {
                                txtConvertedUrls.Text += m.Groups[1].Value + Environment.NewLine;
                            }
                        }
                    }
                }
            }
            catch(WebException we)
            {
                if(we.Status == WebExceptionStatus.ProtocolError && we.Response != null)
                {
                    var resp = (HttpWebResponse)we.Response;
                    if (resp.StatusCode == HttpStatusCode.NotFound)
                    {
                        continue;
                    }
                }
                throw;
            }

错误显示在 continue; 上说 No enclosing loop out of which to break or continue。我不确定如何从这里开始。感谢任何帮助。

那是因为当抛出异常时,你已经离开了foreach块并且你正试图continue但是此时没有循环可以继续。这是您的简化代码以显示这一点:

try {
   foreach( string s in txtInstagramUrls.Lines ) {

   }
}
catch( WebException we ) {
   // There is no loop here to continue
}

您需要将 try 放在循环中:

foreach( string s in txtInstagramUrls.Lines ) {
   try {
      // do something
   }
   catch( WebException we ) {
      continue;
      throw;
   }
}

因此您需要将代码更改为以下内容:

foreach( string s in txtInstagramUrls.Lines ) {
   try {
      if( s.Contains( "something" ) ) {
         using( WebClient wc = new WebClient() ) {
            Match m = Regex.Match( wc.DownloadString( s ), "(?<=og:image\" content=\")(.*)(?=\" />)", RegexOptions.IgnoreCase );
            if( m.Success ) {
               txtConvertedUrls.Text += m.Groups[ 1 ].Value + Environment.NewLine;
            }
         }
      }
   }
   catch( WebException we ) {
      if( we.Status == WebExceptionStatus.ProtocolError && we.Response != null ) {
         var resp = ( HttpWebResponse ) we.Response;
         if( resp.StatusCode == HttpStatusCode.NotFound ) {
            continue;
         }
      }
      throw;
   }

}