Skip to content
umermansoor edited this page Nov 26, 2012 · 3 revisions

Rule: A method should throw all exceptions which it cannot handle (such as Business Rules). All such exceptions (except Runtime exceptions) should be declared as thrown in the method declaration. Don't declare Runtime exceptions in the method signature. Declare them in Javadocs.

The first part of this rule says that you should not catch and gobble up exceptions that you are not handling. You should rather throw such exceptions back to the caller, propagating up the call stack until eventually reaching the handler.

Do not declare Runtime exceptions (e.g. NullPointerException or IllegalArgumentException) in the method signature as they may be misleading to your users. Instead, declare as exceptions as thrown in your Javadocs.

For example, suppose our NumberFilter class which tells us whether we should process an event or not, starts catching exceptions and making decisions on how to proceed. For example:

 public class NumberFilter
 {

     // ... other code

    public boolean allowEvent(event)
    {
        try 
        {
            return checkEventTypeInFile(event);
        }
        catch (IOException e)
        {
            //unable to open file
            return false; // -- bad style here. This function is making decision that it should disallow
                          // all events which cannot be read from the file. Instead it should throw the
                          // exception to the caller and let the caller (Business Rules Engine) make the
                          // decision.
        }
    } 
}

A better way to write the above class is following:

 public class NumberFilter
 {

     // ... other code

    public boolean allowEvent(event) throws IOException // -- inform the caller of the exception and let 
                                                        // it make the final decision
    {
        return checkEventTypeInFile(event);
    }
}