Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added short NCE

...

In this noncompliant code example, a divide by zero exception was handled initially. Instead of the specific exception type ArithmeticException, a more generic type Exception was caught. This is dangerous since any future exception updates to the method signature (such as, addition of IOException here) may no longer require the developer to provide a handler. Consequently, the recovery process may not be tailored to the specific exception type that gets thrown. Additionally, unchecked exceptions under RuntimeException are also unintentionally caught when the top level Exception class is caught.

Code Block
bgColor#FFcccc
import java.io.IOException;

public class DivideException {
  public static void main(String[] args) {
    try {
      division(200,5);
      division(200,0); //divide by zero        
    } catch (Exception e) { System.out.println("Divide by zero exception : " + e.getMessage()); }    	                    
  }

  public static void division(int totalSum, int totalNumber) throws ArithmeticException, IOException  {  
    int average  = totalSum/totalNumber; 
    System.out.println("Average: "+ average);   	
  }
}

Noncompliant Code Example

This noncompliant example improves by catching a specific divide-by-zero exception but fails on the premise that it unscrupulously accepts other undesirable runtime exceptions, by catching Exception.

Code Block
bgColor#FFcccc

try {
  division(200,5);
  division(200,0); //divide by zero        
} catch (ArithmeticException ae) { throw new DivideByZeroException(); }  // DivideByZeroException extends Exception so is checked
  catch (Exception e) { System.out.println("Exception occurred :" + e.getMessage()); }	

Compliant Solution

To be compliant, catching specific exception types is advisable especially when the types differ significantly. Here, Arithmetic Exception and IOException have been unbundled as they belong to very diverse categories.

...