I’ve read a lot of times that one should never blindly catch exceptions. Some people say it’s ok to wrap your Main() into a catch block to display errors instead of just exiting (see this SO post for example), but there seems to be a consensus that you should never let your program running if something unexpected occurred, since it’s in an unknown state, and may act in unexpected ways.
While I agree on the fact that hiding bugs rather than fixing ’em is definitely a wrong idea, consider the following case :
You’ve got a huge server. Million of lines of code.
When it starts, it loads all the Customer into its local cache.
To, me, it makes a lot of sense to write this :
foreach (string CustomerID in Customers) try { LoadCustomer(CustomerID); } catch (Exception ex) // blind catch of all exceptions { // log the exception, and investigate later. }
Without the blind catch, failing to load a single Customer would just crash all the server.
I definitely prefer having my server up with a little unknown side effect on one customer rather than my whole server down.
Of course, if I ever run my catch code, the first thing I’ll do is fix the bug in my code.
Is there something I’m overlooking here? Are there known best practices (other than the ‘never catch unexpected exception’ strategy’?)
Is it better to catch the exception in the LoadCustomer() method, to rethrow a ‘CustomerLoadException’ from there, and to catch CustomerLoadException instead of all Exception in the calling code?
This is a question of Robustness, that is continuing to operate even in the event of unexplainable errors, vs Correctness, prefering to fail completely rather than produce unreliable results.
Clearly if you are working on, for example, life-support systems, you don’t want your system to simply shut down due to an unknown error condition. Cotninuing to operate, even if your state isn’t well defined, is probably better than terminating.
On the other hand, if your program is a shopping cart, it’s probably better to simply fail completely rather than potentially send the wrong item, or charge the wrong amount of money to the wrong individuals.
Everything in between is a gray area and it’s a judgment call. In the main, it would seem that life-support systems programming is more rare than shopping-cart programming, so the broad advice is for people to do what’s most common, which is fail in the event of an unexpected error. It’s understood that if you are working on a case where that’s not appropriate (such as your server example), you will know better.