Similar to another question that was asked on this topic, if you want to catch Exception, you must have a final throw
within the handler in order to prevent the warning from appearing.
From the MSDN documentation on this warning:
To fix a violation of this rule, catch a more specific exception, or
re-throw the general exception as the last statement in the catch
block.
That said, this wouldn't really help in your situation since you want to "swallow" the exception, not rethrow it. Looking at this list of six specific exceptions, I can't imagine that it would be a painful experience to take the time (seriously like five minutes) to handle each of them in the most recommended way possible. It's not like this happens very often, and WebRequest is just one of those rare instances.
If your application will have a significant lifetime, odds are that over time you are going to find yourself implementing handlers for each one of these exceptions. No one likes "a general error 405 occurred" error messages. This may not be KISS, but putting the groundwork in place will give you the benefit of avoiding catching all Exceptions (like OutOfMemoryException
), and will also prevent the FxCop warning (and scorn from picky developers).
If you are generating a lot of WebRequests in your application, perhaps a helper class as follows would be useful that throws a single WebFetcherException
and also has more helpful error messages. Here's an example:
public static class WebFetcher
{
public WebResponse FetchFromUrl(Uri uri)
{
try
{
var request = WebRequest.Create(new Uri("MyUrl")) as HttpWebRequest;
return request.GetResponse();
}
catch (NotSupportedException ex)
{
//you could customize the error messages to be more suitable for your
//application, or leaving room for future error handling
throw new WebFetcherException(ex.Message, ex);
}
catch (ArgumentNullException ex)
{
throw new WebFetcherException(ex.Message, ex);
}
catch (SecurityException ex)
{
throw new WebFetcherException(ex.Message, ex);
}
catch (ProtocolViolationException ex)
{
throw new WebFetcherException(ex.Message, ex);
}
catch (WebException ex)
{
throw new WebFetcherException(ex.Message, ex);
}
catch (InvalidOperationException ex)
{
throw new WebFetcherException(ex.Message, ex);
}
}
public class WebFetcherException : Exception
{
public WebFetcherException(string message, Exception inner)
: base(message, inner)
{ }
}
}