我有多个链接,我想在按下开始按钮时处理所有这些链接。如果其中一个链接返回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
。我不知道如何从这里开始。任何帮助表示赞赏。
答案 0 :(得分:3)
这是因为当抛出异常时,您已经离开了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;
}
}