I know this has been discussed before elsewhere - but since I'm cranky about finding it after not-so-few-minutes of looking in some legacy code I'm working on - what follows is NOT an example of proper exception handling:
This "swallow and forget" approach causes an immense amount of pain for all parties involved. I've been working on some third party code and was troubled by the fact that the Event Viewer had a number of errors in the log, but that I hadn't encountered any blatant errors while using the application. I only knew that every once and a while, the application didn't respond as I expected it to respond. From a developer's perspective, this is annoying and time consuming to pin down. From a business owner's perspective, this inconsistent behavior leads to lost business or worse.
Swallowing the exception is analogous to the "On Error Resume Next" which had many a developer (aka - me) throwing monitors out windows while debugging Active Server Pages way back when and which continues to blemish the VB.NET language. If there's an exception, it should be assumed that something is terribly wrong; otherwise, it wouldn't be called an exception. When exceptions occur, the application should fail and fail fast; and if that can't happen in your application (aka - a pacemaker), then careful attention should be made to ensure that exception recovery is complete, having put the application back into a state as if the exception had not occurred.
Failing fast doesn't have to mean failing ugly. Let's face it, we write bugs in our code. We shouldn't be embarrassed to politely let the user know that something went wrong (that it wasn't their fault), that we've been informed of the problem, and that we'll get back to them in a timely and courteous manner with a resolution. But what we shouldn't be doing is hiding bugs under the rug and keeping our fingers crossed that the application will somehow recover on its own. If you're lucky, the user won't notice that anything happened and will be able to continue. But in most cases, these swallowed exceptions confuse users with erratic behavior (that's erratic application behavior, not erratic users...although they can be problematic as well) and make it hellishly difficult for developers to figure out why the application is behaving as it is.
At bare minimum, use the following as a starting point for better exception handling:
Note that it does not say "throw ex;" The difference is subtle but important. "throw ex;" re-throws the exception and overwrites the stack trace. "throw;" simply allows the exception to pass through as if it had never been caught at all.
As I assume most of you already know this, please lean over and tap the nearest developer to you who doesn't read anything, and tell them you'll beat them with a dead chicken if you ever catch them swallowing exceptions! (Dead chicken optional for any PETA readers out there.)
Billy McCafferty
Posted
11-30-2007 6:36 AM
by
Billy McCafferty