posted on Monday, August 16, 2004 12:20 PM
by
scotts
exception handling feedback
In a recent blog post a question was raised about appropriate exception handling (or the lack there of in most cases).
As a follow-up to that post:
One thing I often try to keep in mind is that it isn’t always possible to look at a given snippet of code, and know immediately if an appropriate decision was made in exception handling. As part of my job, I am sometimes asked to code review and determining if appropriate exception handling was applied can be difficult when reviewing “units of work”.
Exception handling strategy is part of bigger application design decision and picture. There are times when it is clear that a try/finally should be used to ensure that even if something bad happens you are still able to do some cleanup work; like closing a db connection. However, it isn’t always clear that a catch makes sense at this same point unless you know something about the overall picture of a given application’s exception handling. I try to live by a basic rule of thumb that says, leave the exception alone unless I am going to either 1) add some real value to the exception or 2) act as the sink point for the exception. By adding some real value to the exception, it might mean hiding the fact that it was a sql exception. And by sinking the exception it might mean determining how and where to log if appropriate, and/or how and where to inform the user. And these things are not always appropriate to do at every section of code that might be doing something dangerous.
It is sometimes by design that a unit of work (a given method, object, etc) does not handle something that appears to be screaming for some exception handling. For example, if all data access code takes place within the context of a data executer component, then a catch statement at the line of code that is doing some sql stuff in the object being executed might be inappropriate. It might be inappropriate because the executer might be handling the exceptions in a bigger more global way and could be adversely impacted if it doesn’t catch the sql exception. Just a small specific example, but the idea is that it isn’t always appropriate to catch exceptions at the point that it looks obvious that something dangerous is taking place.
Additionally, it can become quite expensive to catch a particular exception and just turn around and throw/re-throw the exception with little or no new additional value added to the exception. Especially if this is done multiple times before something really useful is done or before the user is informed that what they were trying to do failed.