Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: re-write

The merits of exception handling are challenged when programmers do not realize how exceptions should be treated. Imprecise handling can lead to loss of critical information, on the other hand, being too specific can result in verbose (unreadable) codeProgrammers often fall into the trap of suppressing or ignoring checked exceptions. Unless there is a valid reason for ignoring exceptions, such as the client cannot be expected to stage a recovery, it is important to handle them appropriately.

Noncompliant Code Example

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 MarkupAdditionally, unchecked exceptions under {{RuntimeException}} are also unintentionally caught when the top level {{Exception}} class is caught. See \[[EXC32-J. Do not catch RuntimeException]\] for detailsthe programmer leaves the catch block adorned with an ignore comment.

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

Compliant Solution

#FFCCCC

try {
//...
}catch(IOException ioe) { /* ignore */ }

Noncompliant Code Example

Printing the exception's stack trace can be useful for debugging but is equivalent to ignoring the exception, as this noncompliant example demonstratesTo 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.

Code Block
bgColor#ccccff

import java.io.IOException;

public class DivideException {
  public static void main(String[] args) {
    try {
      division(200,5);
      division(200,0); //divide by zero        
    } catch (ArithmeticException ae) { throw new DivideByZeroException(); }  // DivideByZeroException extends Exception so is checked
      catch (IOException ie) { System.out.println("I/O Exception occurred :" + ie.getMessage()); }	    
  }

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

There are several other antipatterns that must be avoided:

  • Do not supress/ignore exceptions: This happens when an empty catch block is defined. The program catches the exception but does not perform any recovery or notification
  • Masking of original exception by a new one: A new exception within a block may in certain cases mask the original exception
  • Logging the same exception more than once: This creates ambiguity while tracing
  • Throwing Exception and Throwable
  • Encapsulating the original exception and throwing a completely new exception from the block

Risk Assessment

#FFCCCC

try {
//...
}catch(IOException ioe) { ioe.printStacktrace(); }

Compliant Solution

This compliant solution attempts to recover from a FileNotFoundException by forcing the user to specify another file when a particular file does not exist in the user-specific directory.

Code Block
bgColor#ccccff

try {
// Requested file does not exist
}catch(IOException) { /* ask the user for a different filename */ }

Exceptions

It is reasonable to ignore an exception which occurs within a catch or finally block, such as while trying to close a FileInputStream object. It is also permissible when the client cannot be expected to recover from the exception easily.

Risk Assessment

Ignoring or suppressing exceptions violates the fail-safe criteria of an applicationNot handling exceptions properly may result in information being lost, problems being overlooked, or too much information being passed to the user.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

EXC00-J

medium low

probable

high medium

P4

L3

Automated Detection

TODO

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

Wiki Markup
\[[JLS 05|AA. Java References#JLS 05]\] [Chapter 11, Exceptions|http://java.sun.com/docs/books/jls/third_edition/html/exceptions.html]
\[[TutorialsBloch 08|AA. Java References#tutorialsReferences#Bloch 08]\] [Exceptions|http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html]
\[[Doshi 03|AA. Java References#Doshi 03]\]
\[[Müller 02|AA. Java References#Müller 02]\]
\[[MITRE 09|AA. Java References#MITRE 09]\] [CWE ID 396|http://cwe.mitre.org/data/definitions/396.html] "Declaration of Catch for Generic Exception", [CWE ID 390|http://cwe.mitre.org/data/definitions/390.html] "Detection of Error Condition Without ActionItem 65: "Don't ignore exceptions"

...

10. Exceptional Behavior (EXC)      10. Exceptional Behavior (EXC)      EXC01-J. Do not allow exceptions to transmit sensitive information