Geeks With Blogs
Amusingly MOSS ...It's funny how difficult some stuff is when it really shouldn't be

Okay, people.  I officially deem it OK to remove someone's geek cred if they put a try block around the entire of a method body.  Furthermore, you get to remove even more geek cred if they just re-throw the error that was caused in the try block.  Here's an example of what I'm talking about:

private void foo()
      // do the foo.
      // do more foo.
      // do the rest of the foo.
   catch (Exception ex)
      throw ex;

Contrary to popular perception, try/catch blocks are not for preventing errors - they are for directing logic flow.  A try/catch block is sometimes treated with special reverence because it revolves around "errors that happen at runtime," and "errors" mean "bugs."  It's an emotional trap everyone falls into - I've even seen project plans that have time allotted for "adding exception handling," as if exception handling were some magic bullet that somehow prevents bugs.

True, when properly implemented, exception handling does reduce the number of "bugs" in the system, but not due to their perceived inherent nature - they reduce bugs the same way adding an "if" construct or a "switch" construct in the correct place will reduce bugs.

It is with this understanding that I believe that try/catch should be treated no differently than any other programming/logic construct.  Would you surround the entire body of a method with an if statement?  If you answered yes, you need to re-think your code.

Here are some rules:


  • Catch only errors for which you plan to take additional action at that point in time.
  • Use a try block only around the code that will cause a fork in logic were an exception to occur.


  • Instance the exception object unless you actually need it.  If catching a type of error is good enough, then don't instance the exception object.
  • Catch errors because you think it will "help out somehow."  Doing so runs the risk of swallowing errors (which make troubleshooting impossible), and adds unnecessary complexity.
  • Re-throw the error that just occurred unless the up-stream code requires it for logging, or any other specific actions.  Re-throwing is expensive, and should be used sparingly.
Posted on Friday, February 27, 2009 2:17 PM Systems Architecture and Design | Back to top

Comments on this post: When not to use exception handling, or, "Don't try too hard"

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Adam McKee | Powered by: