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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s