Woozle Wuzzle
Limit the scope of try-catch blocks

How many times have you seen the following?

public void myMethod(...)
    throws ...
{
    try {
        ... entire method is here ...
    } catch(SomeException se) {
        ....
    }
}

Consider when entire method is here is more than a dozen lines or so with a number of statements that throw SomeException lumped:

Limiting the scope of try-catch blocks forces the developer to think about each exception that can be thrown and how to appropriately handle them. I immediately associate a higher risk (as in QA) with a section of code that is in a single large try-catch block. It is likely that there are statements in that block that throw the caught exception that were never considered. This is a similar case as presented in That nasty java.io.IOException where unexpected exceptions bubble out due to a throws clause.

A common case to watch out for is one where a try-catch block surrounds a loop or vice-versa. The tendancy with a large try-catch block is to miss cases where the exception, if properly caught in a smaller try-catch block, would continue rather than break or vice-versa.

There are cases where a large try-catch block makes sense. Through comments it is a simple matter to indicate the reason why such a choice was made (see Code Comments for more information) thereby reducing the risk associated with the block.

Comments
Post a comment













Remember personal info?






Creative Commons License Unless otherwise expressly stated, all original material of whatever nature created by Rob Grzywinski and included in this weblog and any related pages, including the weblog's archives, is licensed under a Creative Commons License.