C# GetResponse抛出WebException和ex。响应为null
我发现了如何在GetResponse调用中处理WebException的示例,并对如何从WebException响应中提取响应感到困惑。第二个难题是为什么空响应被视为抛出;有什么建议吗C# GetResponse抛出WebException和ex。响应为null,c#,.net,C#,.net,我发现了如何在GetResponse调用中处理WebException的示例,并对如何从WebException响应中提取响应感到困惑。第二个难题是为什么空响应被视为抛出;有什么建议吗 HttpWebResponse response = null; try { response = (HttpWebResponse) request.GetResponse(); } catch (WebException ex) { response = (HttpWebResponse)ex
HttpWebResponse response = null;
try
{
response = (HttpWebResponse) request.GetResponse();
}
catch (WebException ex)
{
response = (HttpWebResponse)ex.Response;
if (null == response)
{
throw;
}
}
响应永远不应该是
null
——在这种情况下,作者说WebException
不能在此异常处理程序中处理,它只是向上传播
但这种异常处理并不理想-您可能想知道发生异常的原因,即:
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
{
var resp = (HttpWebResponse)ex.Response;
if (resp.StatusCode == HttpStatusCode.NotFound) // HTTP 404
{
//file not found, consider handled
return false;
}
}
//throw any other exception - this should not occur
throw;
}