Versions Compared

Key

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

Wiki Markup
            Programs must not catch {{java.lang.NullPointerException}}. A {{NullPointerException}} exception thrown at runtime indicates the existence of an underlying {{null}} pointer dereference that must be fixed in the application code (see rule [ [EXP11-J. Never dereference null pointers|EXP11-J. Never dereference null pointers]).) Handling the underlying null pointer dereference by catching the {{NullPointerException}} rather than fixing the underlying problem is inappropriate for several reasons. First, _avoiding_ the exception by catching {{NullPointerException}} adds significantsignificantly more performance overhead than simply adding the necessary checks \[[Bloch 2008|AA. Bibliography#Bloch 08]\]. Second, when there are multiple expressions in a {{try}} block that are capable of throwing a {{NullPointerException}}, it is difficult or impossible to determine which expression is responsible for the exception because the {{NullPointerException}} {{catch}} block handles any {{NullPointerException}} thrown from any location in the {{try}} block. Third, programs rarely remain in an expected and usable state after a {{NullPointerException}} has been thrown. Attempts to continue execution after first catching and logging (or worse, suppressing) the exception rarely succeed. 

Likewise, programs must not catch RuntimeException, or  or its ancestors Exception or Throwable. Few, if any, methods are capable of handling all possible runtime exceptions. When a method catches RuntimeException, it may receive exceptions unanticipated by the designer, including NullPointerException and ArrayIndexOutOfBoundsException. Many catch clauses simply log or ignore the enclosed exceptional condition , and attempt to resume normal execution; this practice often violates rule ERR00-J. Do not suppress or ignore checked exceptions. Runtime exceptions often indicate bugs in the program that should be fixed by the developer, and often cause control flow vulnerabilities.

...

Each Service object must support the possibility that a Log object may be null, because  because clients may choose not to perform logging. This noncompliant code example eliminates null checks by using a try-catch block that ignores NullPointerException.

...

An acceptable alternative implementation uses a setter method and a getter method to control all interaction with the reference to the current log. The setter ensures use of the null object in place of a null reference. The getter ensures that any retrieved instance is either an actual logger or a null object (but never a null reference). Instances of the Null Object are immutable , and are inherently thread-safe. Classes that provide setter or getter methods , must comply with the second exception of OBJ09-J. Defensively copy private mutable class members before returning their references.

...

Code that uses this pattern must be clearly documented to ensure that security-critical messages are never discarded because the pattern has been misapplied.

...

In this noncompliant code example, the original version of the division() method was declared to throw only ArithmeticException. However, the caller catches a more general type (Exception) to report arithmetic problems , rather than catching the specific exception type (ArithmeticException). This practice is insecure , because future changes to the method signature could add to the list of potential exceptions the caller must handle. In this example, a newer version of the division method can potentially throw IOException in addition to ArithmeticException. However, the compiler cannot tell the caller's developer that he must provide a corresponding handler , because his existing code already catches IOException as a result of catching Exception. Consequently, the recovery process may be inappropriate for the specific exception type that is thrown. Furthermore, the developer has failed to anticipate that catching Exception also catches unchecked exceptions.

Code Block
bgColor#FFcccc
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;
    // Additional operations that may throw IOException...
    System.out.println("Average: " + average);
  }
}

...

This noncompliant code example attempts improvement by specifically catching ArithmeticException. However, it continues to catch Exception, and  and consequently catches both unanticipated checked exceptions and also unanticipated runtime exceptions.

Code Block
bgColor#FFcccc
try {
  division(200, 5);
  division(200, 0); // Divide by zero        
} catch (ArithmeticException ae) { 
  throw new DivideByZeroException(); 
} catch (Exception e) { 
  System.out.println("Exception occurred :" + e.getMessage());
}	

Note that DivideByZeroException is a custom exception type that extends Exception.

...

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 ex) { 
      ExceptionReporter.report(ex);
    }	    
  }

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

Note that DivideByZeroException is a custom exception type that extends Exception.

...

Java 1.7 allows a single catch block to catch multiple exceptions. This allows one catch block to handle exceptions of different types, which prevents redundant code. This compliant solution catches the specific anticipated exceptions (ArithmeticException and IOException) , and handles them with one catch clause. All other exceptions are permitted to propagate to the next nearest dynamically - enclosing catch clause of a try statement.

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|IOException ex) { 
      ExceptionReporter.report(ex);
    }	    
  }

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

Note that DivideByZeroException is a custom exception type that extends Exception.

...

EXC14-EX0: A catch block may catch all exceptions to process them before re-throwing them. For example, rethrowing them (filtering sensitive information from exceptions before the call stack leaves a trust boundary, for example). Refer to rule to ERR06-J. Do not allow exceptions to expose sensitive information, as well as CWE 7 and CWE 388). In such cases, a catch block should catch Throwable rather than Exception or RuntimeException.

This code sample catches all exceptions and wraps them in a custom DoSomethingException before re-throwing rethrowing them.

Code Block
bgColor#ccccff
class DoSomethingException extends Exception {
  public DoSomethingException(Throwable cause) {
    super(cause);
  }
    
  // other methods
};

private void doSomething() throws DoSomethingException {
  try {
    // code that might throw an Exception
  } catch (Throwable t) {
    throw new DoSomethingException(t);
  }
}

...

Wiki Markup
*EXC14-EX1*: Task processing threads such as worker threads in a thread pool or the Swing event dispatch thread are permitted to catch {{RuntimeException}} when they call untrusted code through an abstraction such as {{Runnable}} \[[Goetz 2006 pg 161|AA. Bibliography#Goetz 06], pg. 161\]. 

EXC14-EX2: Systems that require substantial fault tolerance or graceful degradation are permitted to catch and log general exceptions such as Throwable at appropriate levels of abstraction. For example:

...

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

Related Guidelines

MITRE CWE:

CWE ID -230 "Improper Handling of Missing Values"

 

CWE ID -232 "Improper Handling of Undefined Values"

 

CWE ID -690 "Unchecked Return Value to NULL Pointer Dereference"

 

CWE ID -395 "Use of NullPointerException Catch to Detect NULL Pointer Dereference"

MITRE CWE  

CWE ID -396 "Declaration of Catch for Generic Exception"

 

CWE ID -7 "J2EE Misconfiguration: Missing Custom Error Page"

 

CWE ID -537 "Information Exposure Through Java Runtime Error Message"

 

CWE ID -536 "Information Exposure Through Servlet Runtime Error Message"

The Elements of Java Style:

Rule 87: Do not silently absorb a run-time or error exception

...

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="4d417387126c55fe-b2e3e725-4163401c-9005aef3-12003ffd2d3927e3ed1b5924"><ac:plain-text-body><![CDATA[

[[Cunningham 1995

AA. Bibliography#Cunningham 95]]

 

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="5645403306524347-c03cbcc3-426f481c-9ea4acf6-0bfd8e25430bc0cbaa4cefba"><ac:plain-text-body><![CDATA[

[[Doshi 2003

AA. Bibliography#Doshi 03]]

 

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="37ea1da3b990ea4f-4278b821-42464ec0-8f2aaf01-7558c55555223f9abd2af47c"><ac:plain-text-body><![CDATA[

[[Grand 2002

AA. Bibliography#Grand 02]]

Chapter 8, Behavioral patterns, the Null Object

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="319ebb28aefc90c0-95120a75-477f4168-af479222-f405b17968f2f596ec56758b"><ac:plain-text-body><![CDATA[

[[Henney 2003

AA. Bibliography#Henney 03]]

 

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="9ecda314f7ef67f4-4eece282-41ea44f4-b44388a8-4d5111de21bb1c5065a5fc32"><ac:plain-text-body><![CDATA[

[[JLS 2005

AA. Bibliography#JLS 05]]

[Chapter 11, Exceptions

http://java.sun.com/docs/books/jls/third_edition/html/exceptions.html]

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="a6492b695ebbd9bd-e6891250-43734cc2-83dc9505-8dd49a0bb5d8d3958af5dbe0"><ac:plain-text-body><![CDATA[

[[J2SE 2011

AA. Bibliography#J2SE 11]]

Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="136b87c1e446d979-6e3bb4fe-4b9d40fb-85adb726-f28adcac7102ff56e524a008"><ac:plain-text-body><![CDATA[

[[Muller 2002

AA. Bibliography#Muller 02]]

 

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="2bcedfd0e80040a5-fa4ff33c-445a42ca-8f8c8808-2089af2470fa3bdfd1a76d09"><ac:plain-text-body><![CDATA[

[[Schweisguth 2003

AA. Bibliography#Schweisguth 03]]

 

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="84d026de48595cea-f4de380c-41404fa2-ad5f8f3e-b753279b62a6b40eef31e405"><ac:plain-text-body><![CDATA[

[[Tutorials 2008

AA. Bibliography#tutorials 08]]

[Exceptions

http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html]

]]></ac:plain-text-body></ac:structured-macro>

...