Question

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!

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top