Strict Exception Rules

The Strict Exception ruleset contains a collection of strict rules concerning exceptions.

AvoidCatchingThrowable

This is dangerous because if a java.lang.Error, for example OutOfMemmoryError, occurs then it will be caught. The container should handle java.lang.Error. If application code will catch them, try to log them (which will probably fail) and continue silently the situation will not be desirable.

Here's an example of code that would trigger this rule:

 
                
SimpleDateFormat sdf = null;
try {
    sdf = new SimpleDateFormat("yyyy-MM-dd");
} catch (Throwable th) {  //Should not catch throwable
    th.printStackTrace();
}
                
       

SignatureDeclareThrowsException

It is unclear which exceptions that can be thrown from the methods. It might be difficult to document and understand the vague interfaces. Use either a class derived from RuntimeException or a checked exception.

Here's an example of code that would trigger this rule:

 
                
public void methodThrowingException() throws Exception {
}
                
       

ExceptionTypeChecking

At some places Exception is caught and then a check with instanceof is performed. This result in messy code. It's considered better to catch all the specific exceptions instead.

Here's an example of code that would trigger this rule:

 
                
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
try {
    returnString = sdf.format(value);
} catch (Exception ex) {
    /* BAD STUFF !!!*/
    if (ex instanceof NumberFormatException) {
        System.out.println("NumberFormat exception!!!");
    }
    if (ex instanceof IllegalArgumentException) {
        System.out.println("illegal argument...!!!");
    }
}