GetResponse throws WebException and ex.Response is null

I found an example of how to handle a WebException when calling GetResponse, and am puzzled by how the response can be retrieved from the WebException Response. The second puzzle is why the null answer is interpreted as throw; Any suggestion?

HttpWebResponse response = null;
try
{
    response = (HttpWebResponse) request.GetResponse();
}
catch (WebException ex)
{
    response = (HttpWebResponse)ex.Response;
    if (null == response)
    {
        throw;
    }
}
+5
source share
1 answer

There should never be an answer null- in this case, the author says that WebExceptionhe cannot be handled in this exception handler, and he simply propagates upwards.

However, this exception handling is not ideal - you probably want to know why the exception occurred, i.e.:

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;
}
+5
source

All Articles