Without knowing more about your application design, specifically exception handling further up the call stack, it is hard to say why it is behaving like it is when you are at home.
But when I just tried your exact code, it did throw a WebException
, however httpResponse.StatusCode
throws a NullReferenceException
because httpResponse
is null. If you are potentially swallowing this exception further up the call stack, it could explain the situation you are seeing.
httpResponse
is going to be null in many WebException
cases because your request did not receive any response, specifically in the timeout scenario.
Before casting WebException.Response
, you need to check the WebException.Status
property. If that status suggests a response was received, then you can go check WebException.Response
, otherwise it is just going to be null. Try something like:
if(e.Status == WebExceptionStatus.ProtocolError) {
listBox.Items.Insert("Status Code : {0}",
((HttpWebResponse)e.Response).StatusCode);
}
else
{
listBox.Items.Insert("Status : {0}", ex.Status);
}
As a side note, your response2.Close();
is never going to be called when HttpWebResponse response2 = (HttpWebResponse)request2.GetResponse();
throws an exception, so you should be wrapping it in a using block:
using(HttpWebResponse response2 = (HttpWebResponse)request2.GetResponse())
{
// do something with response
}