1

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.

Community
  • 1
  • 1
newprint
  • 6,936
  • 13
  • 67
  • 109
  • 1
    For your "another case": `WebRequest.Create("ftp://some.site") as HttpWebRequest` will indeed return null - "The Create method returns a descendant of the WebRequest", but not necessary `HttpWebRequest` all the time. – Alexei Levenkov Jul 01 '14 at 15:55
  • @AlexeiLevenkov, Well, if WebRequest.Create("address") returns null, that means scheme is not supported. Wouldn't it better to just let `WebRequest.Create()` throw `NotSupportedException` exception ? Edit: well, Not necessary...... if you request ftp address, and expect `HttpWebRequest` as response(`as HttpWebRequest`), that yes. `null` would be a better choice ! – newprint Jul 01 '14 at 17:56

1 Answers1

1

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.

Belogix
  • 8,129
  • 1
  • 27
  • 32