Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# GetResponse抛出WebException和ex。响应为null_C#_.net - Fatal编程技术网

C# GetResponse抛出WebException和ex。响应为null

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

我发现了如何在GetResponse调用中处理WebException的示例,并对如何从WebException响应中提取响应感到困惑。第二个难题是为什么空响应被视为抛出;有什么建议吗

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;
}