Editorials

Exception/Error Handling

Today I am going into territory where I find I still have much to learn. That is the topic of actually capturing and handling errors. Previously we talked about tracking and notification of errors. Today, we are transitioning to when and how to capture exceptions and errors.

I’d say different kinds of programs have different needs. A Service, or long running program, may need an exception handling routine wrapping over all activities. You may not want a service to stop simply because a routine was added to your program without adequate error handling. I’m not saying there should be no error handling at a more granular level. I’m suggesting that you may want to have a last ditch handler, keeping your service from crashing, because something was missed, or not considered.

By contrast, an executable, where the user is in direct contact, may not need such a global handler. It may be fine for the program to end with an error, if it really has no more work that may be done due to the error.

In the opposite extreme, I observed a developer’s code once, having unique error handling in every method, and then re-throwing that error to be handled in the calling routine. The code was difficult to handle, and you received an error for each layer of the stack trace, with little value.

From my experience I find I capture errors and exceptions at the highest level possible, and the lowest level necessary. In other words, my intention is to provide as much information possible to resolve the exception, either by the user, or by giving necessary information for debugging code. When the user attempts to save data and it fails, they need to know what to do next. When the programmer needs to know why the save failed, they require a lot more detailed information.

So, when I create error handling, I find my most detailed error handling at a lower level in the code, and this often is written to a log of some sort. I then throw the error again. The higher level code, not concerned with data persistence, but simply firing off a persistence request, captures the error again, and returns a more friendly error response to the user, providing directions as best possible.

Consider a deadlock persistence error. I want to log what I can when my processes is elected as a deadlock victim. This helps me determine what processes were running resulting in the deadlock. However, for the user, I know that a deadlock failed to save, but, they can try again, and probably succeed. This is much different than when the database is offline. Having received this kind of error the response to the user should be much different.

Folks, this is just a lot of my thoughts. I’d sure like to hear from you. I’m sure you have suggestions to make this better, or correct some holes I may have missed. So, drop an email to btaylor@sswug.org, or leave a comment online.

Cheers,

Ben