Methods must not throw RuntimeException
, Exception
, or Throwable
. Handling these exceptions requires catching RuntimeException
, which is disallowed by rule 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.
...
The isCapitalized()
method in this noncompliant code example accepts a string and returns true when the string consists of a capital letter followed by lowercase letters. The method also throws a RuntimeException
when passed a null string argument.
Code Block | ||
---|---|---|
| ||
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()));
}
|
A calling method must also violate rule ERR08-J. Do not catch NullPointerException or any of its ancestors to determine whether the RuntimeException
was thrown.
...
This compliant solution throws NullPointerException
to denote the specific exceptional condition.:
Code Block | ||
---|---|---|
| ||
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 specifies the Exception
class in the throws
clause of the method declaration for the doSomething()
method.:
Code Block | ||
---|---|---|
| ||
private void doSomething() throws Exception {
//...
}
|
...
This compliant solution declares a more specific exception class in the throws
clause of the method declaration for the doSomething()
method.:
Code Block | ||
---|---|---|
| ||
private void doSomething() throws IOException {
//...
}
|
...
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
ERR07-J | low Low | likely Likely | medium Medium | P6 | L2 |
Related Guidelines
Bibliography
...