Methods are forbidden to must not throw RuntimeException
or Exception
. Handling these exceptions requires catching RuntimeException
, which is forbidden in guideline disallowed by rule ERR14-J. Do not catch RuntimeException. 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, Methods can 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 that calls this method must catch RuntimeException
, which violates guideline A calling method must violate rule ERR14-J. Do not catch RuntimeException to handle null
string arguments to the method.
Compliant Solution
This compliant solution throws a specific exception (NullPointerException
) to denote the particular exceptional condition.
...
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 | ||
---|---|---|
| ||
private void doSomething() throws Exception { //... } |
Compliant Solution
To be compliant, be as specific as possible when declaring exceptions while continuing to respect the required abstraction levelThis compliant solution declares a specific exception in the throws
clause of the method declaration for the doSomething()
method.
Code Block | ||
---|---|---|
| ||
private void doSomething() throws IOException { //... } |
Using instanceof
to check for narrower exceptions in a general catch
block is often insufficient; inadequate because it is usually frequently impossible to enumerate all possible exceptions that the code could throw.
...