I have a problem with httpwebrequest exception. I use the following code to make a request and catch the exception.
try
{
Uri url= new Uri("https://www.example.com");
HttpWebRequest request2 =(HttpWebRequest)WebRequest.Create(url);
request2.Timeout = 10000;
HttpWebResponse response2 = (HttpWebResponse)request2.GetResponse();
response2.Close();
}
catch (TimeoutException)
{
listBox.Items.Insert(0, "Timeout");
}
catch (WebException ex)
{
using (WebResponse response = ex.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
listBox.Items.Insert(0, "Status code(Benchmark):" + httpResponse.StatusCode);
}
}
catch
{
listBox.Items.Insert(0, "Failure");
}
At company network when I enter a non-existing url such as http://www.oiuahsdupiasduiuhid.com; it throws webexception . I got status code: not found or service unavailable. However If I try it at home, it doesn’t throw any exception. It waits around 1 second and then without any error stops working. I delete all exceptions to see what is happening but the problem is it doesn’t show any error.
Do you have any idea about what is the problem?
Or any recommendation, how can I handle this problem with a different way?
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, howeverhttpResponse.StatusCodethrows aNullReferenceExceptionbecausehttpResponseis null. If you are potentially swallowing this exception further up the call stack, it could explain the situation you are seeing.httpResponseis going to be null in manyWebExceptioncases because your request did not receive any response, specifically in the timeout scenario.Before casting
WebException.Response, you need to check theWebException.Statusproperty. If that status suggests a response was received, then you can go checkWebException.Response, otherwise it is just going to be null. Try something like:As a side note, your
response2.Close();is never going to be called whenHttpWebResponse response2 = (HttpWebResponse)request2.GetResponse();throws an exception, so you should be wrapping it in a using block: