Please consider the following piece of code, which throws three different exceptions (namely, System.Configuration.ConfigurationErrorsException, System.FormatException and System.OverflowException):
int SomeInt = Convert.ToInt32(ConfigurationManager.AppSettings["SomeIntValue"]);
The exceptions are different, and so in practice I should have three different catch blocks to handle each particular exception. However, in this particular case, all exceptions are handled the same way: a log is written to, say, EventViewer, and a message informing of a configuration error is displayed… In this particular cause, is it too bad to use
try
{
int SomeInt = ConfigurationManager.AppSettings["SomeIntValue"];
}
catch (Exception ThisException)
{
/* Log and display error message. */
}
or should I, instead, use the three catch blocks and repeat the code within each of them?
I don’t think it’s bad practice. If your desired functionality is “whenever this code throws an exception, then take these actions” then I think catching System.Exception is perfectly appropriate.
The fact that you’re wrapping a very specific framework function instead of a large block of custom code helps in my opinion as well.