Fresh Blurbs

Exception Handling and the Chain of Responsibility Design Pattern

Developers often compain about explicit Exceptions, especially in a strongly typed language like Java, and how much real estate handling those takes up in source code.

I have seen approaches when people try to avoid java.lang.Exception and fall back to java.lang.RuntimeException for most cases. Is that a good thing to do? RuntimeException is a valid choice for certain cases but overusing it beats the whole idea of exception-handling, really.

As part of my responsibilites as a software architect, I get to review code of many developers. I think the problem, in most cases, is incorrect usage of exception-handling. More specificly, developers overdo with catching exceptions at the lowest level - at the same spot they expect exception to be fired. Passing it up the class hierarchy is often needed but not done. It is especially true in the case of more junior developers (however, you quickly find out that many "senior" developers are vulnarable, as well).

If you look at a software system, especially a web-application and more so a well-design one, it is, basically, an implementation of the Chain of Responsibility pattern for different use-cases. Developer immidiately catching an exception wherever it is fired is often a bad thing to do. In many cases, a much more correct (and elegant) approach is to pass it up the chain of responsibility. Unfortunately, if you look at a common code, you rarely see a method declared with "throws" keyword. So, a lot of times, developers try to handle exception in the lowest methods and do not pass it up the chain. That's bad. Many errors can/should be grouped and handled uniformally.

For instance, when you have a database transaction that spans across several methods, do not try to handle JDBC/Hibernate/EJB exceptions in each method - declare a sensible exception subclass and pass it up, at least to the class that is handling the entire transaction. Then the upper-level class can handle all these exceptions and make a decision of rolling back the entire transaction, which in most cases is what should happen, indeed.

Bottomline: "throws" is just as useful as try/catch - use it!

comments powered by Disqus