You do not want to catch every exception everywhere.
You want to prevent exceptions from "leaking out" of the lower layers of your application up to where they can kill the application or corrupt it.
But preventing corruption is going to require more than just catching exceptions. You're going to have to make sure that the application is always safe to interrupt at every point where an exception could be thrown. This may mean that you need to clean up complicated operations. For example:
ComplexBuilder cb = new ComplexBuilder();
try
{
cb.AddOperation(...); // Once building starts,
cb.AddOperation(...); // it's not safe to use cb
cb.AddOperation(...);
}
catch (SpecificException ex)
{
cb.Cleanup(); // until it's cleaned up
}
// Now safe to access cb, whether or not an exception was thrown
I recently ran into an application with a similar attitude. There was piece of this application that was considered to be "important". When that "important" thing happened, there were other things that were supposed to happen, but which were considered "not important". The idea was that if there was an exception in the "not important" part, then it was necessary for the "important" part to continue.
What happened is that an attempt to read a resource failed for some reason. This returned null instead of the string resource. This caused an ArgumentNullException
in a String.Format
call. This caused the exception to be caught by code that just continued.
But between the first exception and the last one, an object was to have been allocated, and the reference to the object was to have been set. But because of the exception, setting the reference never happened. The result was that I saw a NullReferenceException
, four stack levels up, and two .csproj files away from where the actual problem happened.
So when you talk about catching exceptions so that your program can continue, you need to keep in mind that the control flow of your program is changed drastically by catching all these exceptions. In fact, it could be changed so much that you can no longer determine whether it's safe for your program to continue executing.