Monday, September 15, 2008

Exception Handling Thoughts

I have discovered over the past couple months that people seem to like to wrap exceptions around larger "units" of code, such as the catching the exceptions in the controller of an MVC framework where the controller can call many functions underneath it. I have one thing to say about this: I don't like it.

There, I said it. To me, it seems very counter-intuitive to do this. If a method throws an exception, shouldn't you catch it right away? That's what I always thought. Now, people may argue about why you should do that and that you can't handle errors at such a low level, however I do believe I have one important reason to catch them as early as possible: state.

You see, how do you know what was passed into a method at a low level when you're 6 levels above it? Easy, you can't. Granted, I do see benefits in capturing exceptions at a higher level. Mainly, I see that it's a consistent location to display messages to the user. However, at the lower level you can do the following:
  1. Determine what the error really is with better accuracy.
  2. Log the state of the system at the time of the error.
  3. Handle the error appropriately, where "handling" the error may be retrying the code or simply rethrowing the error.
  4. Unit tests are performed at a lower level, so you can't rely on the high level exception handler to do anything useful with an exception. Capturing exceptions sooner than later means you don't have to wade through stack traces to figure out what happened.
Now, another thing you can do is capture exceptions all the way up the to the highest level. This way you can capture very detailed information about the state of the system and know exactly how what path you took through your program.

Why am I so upset with the current exception handling situation? Easy: I hate Java stack traces. They are god awful to read and at times tell you nothing useful. If someone where to put exception handling in their code at a lower level, I can get a better idea of what went wrong provided that the user did their job properly. I have enough problems with Java since I don't code it in very often so don't make my life harder.

Labels: ,


Post a Comment

Links to this post:

Create a Link

<< Home