Versions Compared

Key

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

...

Likewise, a method should never catch Exception or Throwable, since this implies catching RuntimeException.

Noncompliant Code Example

The following function takes a string and returns true if it consists of a capital letter succeeded by lowercase letters. To handle corner cases, it merely wraps the code in a try/catch block and reports any excepts that arise.

Code Block
bgColor#ffcccc

boolean isCapitalized(String s) {
  try {
    String first = s.substring( 0, 1);
    String rest = s.substring( 1);
    return (first.equals( first.toUpperCase()) &&
	    rest.equals( rest.toLowerCase()));
  } catch (RuntimeException exception) {
    ExceptionReporter.report( exception);
  }
  return false;
}

This code will report errors such as if s is a null pointer, or is the empty string. However, it will also catch other errors unlikely to be handled properly, such as if the string belongs to a different thread.

Compliant Solution

Intead of catching RuntimeException, a program should catch very specific exceptions.

Code Block
bgColor#ccccff

boolean isCapitalized(String s) {
  try {
    String first = s.substring( 0, 1);
    String rest = s.substring( 1);
    return (first.equals( first.toUpperCase()) &&
	    rest.equals( rest.toLowerCase()));
  } catch (NullPointerException exception) {
    ExceptionReporter.report( exception);
  } catch (IndexOutOfBoundsException exception) {
    ExceptionReporter.report( exception);
  }
  return false;
}

This code will only catch exceptions intended by the programmer to be caught. A concurrency-based exception will not be caught by this code, and can therefore be managed by code more specifically designed to handle it.

Risk Assessment

Catching RuntimeException will trap several types of exceptions not intended to be caught. This prevents them from being handled properly.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

EXC32-J

low

likely

medium

P6

L2

Automated Detection

TODO

Related Vulnerabilities

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

References

...

EXC03-J. Try to recover gracefully from system errors      10. Exceptional Behavior (EXC)      EXC30-J. Do not exit abruptly from a finally block