0

HttpWebRequest.GetReponse() has 4 types of Exceptions MSDN:
- System.InvlaidOperationException
- System.Net.ProtocalViolationException
- System.NotSupportedException
- System.Net.WebException

I'd like to catch all exceptions thrown by GetResponse() either with one catch{} for all GetResonse() exceptions or a catch{} for each type of exception thrown by GetResponse(), and catch all other exceptions with another catch{}.

In everything I've read, I only see WebException being caught. Is that because it catches everything that GetResponse() throws or because the other exceptions are more generic and will be thrown by others?

Consider the following code:

try  
{
    //a bunch of code...
    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    //the rest of the try block...
}
catch (WebException e)
{
    Console.WriteLine("You caught a WebException: " + e.Message);
    throw;
}
catch (Exception e)
{
    Console.WriteLine("This exception was not from getResponse: " + e.Message);
    throw;
}

*I throw intentionally here. It needs to be dealt with by other callers further up the stack.

Alternatively, to catch all exceptions thrown by GetResponse, would I do something like this?

catch (WebException e)
{
    Console.WriteLine("You caught a WebException: " + e.Message);
    throw;
}
catch (InvalidOperationExceltion e)
{
    // Do stuff...
}
catch (ProtocolViolationException e)
{
    // Do stuff...
}
catch (NotSupportedException e)
{
    // Do stuff...
}
catch (Exception e)
{
    // Do stuff...
}

I'm sure it's just as straightforward as I think it is, but I can't find examples of people catch more than WebException.

Thanks!

Joshua Lee
  • 23
  • 3

1 Answers1

0

Use the second code, but why would you handle all other exceptions when you're already handling the exceptions thrown by GetResponse? The extra "catch" is unneccessary IMO.

  • Good question. The code above is a little misleading. The try-catch in my real code is around a call to a method that actually does the GetResponse() and has other functional code in it that could also fail. The generic catch holds specific logging code. – Joshua Lee Mar 23 '14 at 21:48
  • Unless there is a way to pass an object argument into one catch{} that encompasses all possible exceptions from getResponse() (vs. an if statement inside the catch), than I will mark this as solved! Thanks for your prompt answer Anwarrex! – Joshua Lee Mar 23 '14 at 22:00
  • Solution might be stated here? http://stackoverflow.com/questions/136035/catch-multiple-exceptions-at-once –  Mar 24 '14 at 08:31
  • Similar question in that thread. I guess the simplified way to ask my question would be: Can exceptions types be grouped by the thrower and caught? – Joshua Lee Mar 27 '14 at 20:58
  • Example: methodExceptions = Exception.type.fromMethod(fooMethod) – Joshua Lee Mar 27 '14 at 21:57
  • Not sure, try it out. –  Mar 28 '14 at 16:49