我有下面的函数将通过代理给我一些网站的html源代码,它的工作正常,除了一些时候,服务器返回503(服务器不可用)或任何其他异常,它从来没有进入catch语句。
在catch语句中,假设函数递归地调用自己,最多调用4次,如果请求在4次尝试后仍然失败,则返回null。
private static string GetPageHTML(string link,bool useprx)
{
int tryCount = 0;
WebClient client = new WebClient() { Proxy = new WebProxy(ProxyManager.GetProxy()) { Credentials = new NetworkCredential("xx", "xx") } };
try
{
return client.DownloadString(link);
}
catch (WebException ex)
{
var statuscode = ((HttpWebResponse)ex.Response).StatusCode;
{
if (tryCount == 3)
{
return null;
}
switch (statuscode)
{
case (HttpStatusCode.Forbidden):
tryCount++;
System.Threading.Thread.Sleep(5000);
return GetPageHTML(link, useprx);
case (HttpStatusCode.NotFound):
return null;
case (HttpStatusCode.GatewayTimeout):
tryCount++;
System.Threading.Thread.Sleep(5000);
return GetPageHTML(link, useprx);
case (HttpStatusCode.ServiceUnavailable) :
tryCount++;
System.Threading.Thread.Sleep(5000);
return GetPageHTML(link, useprx);
default: return null;
}
}
}
}那么为什么它从来不会进入catch语句呢?
发布于 2013-03-28 13:38:04
它可能返回一个不属于WebException类型的异常。要捕获太阳下的所有异常,您必须包括“捕获异常”作为备用方法
在WebException捕获之后添加回退捕获,并对其进行调试,以查看它真正返回的异常类型
https://stackoverflow.com/questions/15674914
复制相似问题