Methods are forbidden to throw from throwing RuntimeException
or Exception
; handling . Handling these exceptions requires catching RuntimeException
, which is forbidden in guideline EXC14-J. Catch specific exceptions rather than the more general RuntimeException or Exception. Moreover, throwing a RuntimeException
can lead to subtle errors, for instance, a caller cannot examine the exception to determine why it was thrown, and consequently cannot attempt recovery.
Instead, prefer throwing throw a more specific exception, subclassed from Exception
. Note that it is permissible to construct an exception class specifically for a single throw
statement.
...
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())); } |
To properly handle the case of passing in a null
string parameter, any code calling that calls this method may require catching must catch RuntimeException
, which is a violation of violates guideline EXC14-J. Catch specific exceptions rather than the more general RuntimeException or Exception.
...
Code Block | ||
---|---|---|
| ||
boolean isCapitalized(String s) { if (s == null) { // redundant; shown for clarity throw new NullPointerException();// redundant; shown for clarity } // redundant; shown for clarity 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())); } |
Although the explicit throw statement is redundant in this small example, more Actually the null check is redundant, if the null check were removed, then the next call (s.equals("")
) would throw a NullPointerException
if s
was null. However, the explicit null check is good form, as it explicitly signifies the code's intention. More complex code may require explicit testing of invariants and appropriate throw statements.
...