I’ve got some UI code that looks like this:
try
{
SomeClass classInstance = new SomeClass(someId);
}
catch (Exception exception)
{
// Content wasn't created, show a message, stop processing
return;
}
It seems the try catch was added because the constructor for SomeClass would bomb out if the someId it receives isn’t valid, and data couldn’t be found in a DB.
Running this code through FXCop recently, it warns against using the general Exception, but all SomeClass does is throw a new Exception with a message to say it failed to initialize.
I guess the problem is that the class constructor should have it’s own custom exception, which I could then handle in my UI, but I wonder what else I could do to the code above to handle the exception, that meets FXCop requirements?
FxCop’s rule exists because the
catch (Exception)block above catches all possible exceptions, including low-level exceptions likeStackOverflowExceptionthat you probably can’t catch in a useful way.The right approach is definitely to throw a more specific type: either one you’ve invented, or an existing .NET framework exception type that closely matches your situation. (When in doubt, I normally go for
InvalidOperationException.)Alternatively, you could check the exact exception type when catching it. This won’t prevent the FxCop warning, but it should address the underlying problem: