Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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.

Wiki Markup
Additionally, unchecked exceptions under {{RuntimeException}} are also unintentionally caught when the top level {{Exception}} class is caught. See \[[EXC32-J. Do not catch RuntimeException]\] for details.

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);   	
  }
}

...