Refactoring Hazards – the Dead Exception

Often while wandering through the code you will come across some nasty looking weeds, and the dead exception anti pattern is a pretty nasty looking weed.

I classify them two ways. The first is the standard empty catch block. The developer has been day dreaming about his girlfriend, the Dow Jones or whatever, and has just forgotten to handle the exception, or has decided that handling the exception is unimportant, or has no idea what an exception is.

The second situation is where the developer has decided that exceptions are just not on, and has decided to panel-beat the code to make all exceptional cases live inside the conditional world. Usually this has been done by disgruntled C developers, and people who have no idea what exceptions are.

What is important to note, is that fixing this problem by propogating exceptions correctly is NOT a refactoring. It is intrinsically changing the behaviour of the code. A careful analysis needs to be done on all calls to that method.

In the first case it is usually a good idea to fix the exception handling. If the method comes from an interface that does not allow the exception to be propogated then throw a RuntimeException.

The second case is more tricky because, as is usually the case, outside the method, a check is being done on NULL (or whatever) to see if an error has occurred in the method. Things typically seen are :

Whatever is being done outside the method needs to be moved inside the method and into the catch block. Or if that is too difficult, replace the conditional check of if(o == null) or if(o == -1) or whatever, with a catch from a try that surrounds myMethod(). In turn the catch section in myMethod() throws a specific Application of System level exception.

It is important to note that converting exception code that is behaving conditionally, into exception code that is behaving like true exception handling, is not a true refactoring, and care must be taken in changing the code.


Posted in Refactoring | Tagged , , | Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

THREE_COLUMN_PAGE