Versions Compared

Key

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

Methods must not throw RuntimeException, Exception, or Throwable. Handling these exceptions requires catching RuntimeException, which is disallowed by ERR08-J. Do not catch NullPointerException or any of its ancestors. Moreover, throwing a RuntimeException can lead to subtle errors; for example, a caller cannot examine the exception to determine why it was thrown and consequently cannot attempt recovery.

Methods can throw a specific exception subclassed from Exception or RuntimeException. Note that it

Wiki Markup
A method should rarely throw {{RuntimeException}} or {{Exception}}. This is because handling these exceptions requires catching {{RuntimeException}}, which is forbidden in [EXC14-J. Catch specific exceptions as opposed to the more general RuntimeException]. Moreover, throwing a {{RuntimeException}} can lead to subtle errors such as a caller who fails to retrieve a return value from an offending method, is unable to check for appropriate feedback. The Java Language Specification (Section 8.4.7 Method Body) allows the declaration of a method with a return type without making it necessary to return a value if a runtime exception is thrown from within the method \[[JLS 05|AA. Java References#JLS 05]\].

Instead, prefer throwing a more specific exception, subclassed from Exception. It is permissible to construct an exception class specifically for a single throw statement.

Noncompliant Code Example

This The isCapitalized() method in this noncompliant code example takes accepts a string and returns true if it when the string consists of a capital letter followed by lowercase letters. To handle corner cases, it checks for the exceptional conditions and throws exceptions if they are likely to disrupt the normal operationThe method also throws a RuntimeException when passed a null string argument.

Code Block
bgColor#ffcccc

boolean isCapitalized(String s) {
  if (s == null) {
    throw new RuntimeException("Null String");
  }
  if (s.equals("")) {
    return true;
  }
  String first = s.substring(0, 1);
  String rest = s.substring(1);
  return (first.equals(first.toUpperCase()) &&
          rest.equals(rest.toLowerCase()));
}

To handle the case of passing in a null string parameter, code calling this method may require catching RuntimeException, which is a violation of EXC14-J. Catch specific exceptions as opposed to the more general RuntimeExceptionA calling method must also violate ERR08-J. Do not catch NullPointerException or any of its ancestors to determine whether the RuntimeException was thrown.

Compliant Solution

This compliant solution devotes a specific exception (throws NullPointerException) to denote the particular specific exceptional condition.:

Code Block
bgColor#ccccff

boolean isCapitalized(String s) {
  if (s == null) {
    throw new NullPointerException();
  }
  if (s.equals("")) {
    return true;
  }
  String first = s.substring(0, 1);
  String rest = s.substring(1);
  return (first.equals(first.toUpperCase()) &&
          rest.equals(rest.toLowerCase()));
}

Note that the null check is redundant; if it were removed, the subsequent call to s.equals("") would throw a NullPointerException when s is null. However, the null check explicitly indicates the programmer's intent. More complex code may require explicit testing of invariants and appropriate throw statements.

Noncompliant Code Example

This noncompliant code example uses a broad specifies the Exception class in the throws clause of the method declaration of for the doSomething() method.:

Code Block
bgColor#ffcccc

private void doSomething() throws Exception {
  //...
}

Compliant Solution

To be compliant, be as specific as possible when declaring exceptions and respect the required abstraction level.This compliant solution declares a more specific exception class in the throws clause of the method declaration for the doSomething() method:

Code Block
bgColor#ccccff

private void doSomething() throws IOException {
  //...
}

Exceptions

ERR07-J-EX0: Classes that sanitize exceptions to comply with a security policy are permitted to translate specific exceptions into more general exceptions. This translation could potentially result in throwing RuntimeException, Exception, or Throwable in some cases, depending on the requirements of the security policyUsing instanceof to check for narrower exceptions in a general catch block is not always helpful because it is usually impossible to enumerate all the exceptions that the code is capable of throwing.

Risk Assessment

Throwing RuntimeException and , Exception, or Throwable prevents classes from catching the intended exceptions without catching other unintended exceptions as well.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

EXC13

ERR07-J

low

Low

likely

Likely

medium

Medium

P6

L2

Automated Detection

...

TODO

Related Vulnerabilities

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

References

Wiki Markup
\[[MITRE 09|AA. Java References#MITRE 09]\] [CWE ID 397|http://cwe.mitre.org/data/definitions/397.html] "Declaration of Throws for Generic Exception", [CWE ID 537|http://cwe.mitre.org/data/definitions/537.html] "Information Leak Through Java Runtime Error Message"
\[[Goetz 04b|AA. Java References#Goetz 04b]\]
\[[Tutorials 08|AA. Java References#Tutorials 08]\] [Unchecked Exceptions — The Controversy|http://java.sun.com/docs/books/tutorial/essential/exceptions/runtime.html]

ToolVersionCheckerDescription
CodeSonar
Include Page
CodeSonar_V
CodeSonar_V

JAVA.STRUCT.EXCP.BROAD

Broad Throws Clause (Java)

Parasoft Jtest
Include Page
Parasoft_V
Parasoft_V
CERT.ERR07.NTX
CERT.ERR07.NTERR
Avoid declaring methods to throw general or unchecked Exception types
Do not throw exception types which are too general or are unchecked exceptions
SonarQube
Include Page
SonarQube_V
SonarQube_V
S112Generic exceptions should never be thrown

Related Guidelines

MITRE CWE

CWE-397, Declaration of Throws for Generic Exception

Bibliography


...

Image Added Image Added Image AddedEXC14-J. Catch specific exceptions as opposed to the more general RuntimeException      13. Exceptional Behavior (EXC)      EXC12-J. Do not allow unsanitized user input to be logged