newprint
newprint

Reputation: 7136

Properly handling exceptions generated by WebRequest and WebReponse in .NET

While browsing through the MS examples and Stackoverlow examples on how to handle exceptions generated by WebRequest (HttpWebRequest) and WebReponse(HttpWebResponse), I found a lot of examples that either handle exceptions or don't handle exceptions.

One example, I found very interesting was https://stackoverflow.com/a/137300/465292 using within using

Another, example (from https://stackoverflow.com/a/3279967/465292)

var request = WebRequest.Create(requestUri) as HttpWebRequest;
                  if (request != null)

seems bogus to me, since no where in doc. http://msdn.microsoft.com/en-us/library/bw00b1dc%28v=vs.110%29.aspx, WebRequest.Create() returns null

Microsoft own example http://msdn.microsoft.com/en-us/library/es54hw8e%28v=vs.110%29.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1, places both WebRequest & WebReponse in one try block.

Upvotes: 1

Views: 91

Answers (1)

Belogix
Belogix

Reputation: 8147

In short, it depends. The point of a try / catch block is if you think you can recover from the exception thrown at that point in time. I.e. Will you be re-trying as you suspect the web call should work and want to give it a couple of goes before giving up?

This is a case by case basis. If an exception occurs and you cannot / do not want to handle it then don't bother wrapping in try / catch and let it go up until something can handle it.

As with using this allows you to release memory and nested usings are fine as it ensures you are disposing of objects where possible. Of course, depending on what you do you might want to go down the try / catch / finally and dispose explicitly in finally but again, a case by case deal.

Upvotes: 1

Related Questions