Wiki Markup |
---|
A method should never throw {{RuntimeException}} or {{Exception}}. This is because handling these requires catching {{RuntimeException}}, which is forbidden in [EXC32-J. Do not catch RuntimeException]. Moreover, throwing a {{RuntimeException}} can lead to subtle errors such as a caller who fails to retrieve a return value from thean 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, always throw an exception subclassed from Exception
. It is permissible to construct an exception class specifically for a single throw
statement.
Noncompliant Code Example
The following function takes a string and returns true
if it consists of a capital letter succeeded followed by lowercase letters. To handle corner cases, it checks for them the conditions and throws exceptions if they would are likely to prevent normal analysis.
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())); } |
In order to handle the case of passing in a null
string parameter, code calling this function would have to catch may require catching RuntimeException
, which violates is a violation of EXC32-J. Do not catch RuntimeException.
Compliant Solution
An exception specifically devoted to the error would be is more appropriate.
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())); } |
...
This noncompliant code snippet uses a broad Exception
class in the throws
statement within declaration of the method declaration.
Code Block | ||
---|---|---|
| ||
private void doSomething() throws Exception { //... } |
...
To be compliant, be as specific as possible while when declaring exceptions and heed respect the given required abstraction level.
Code Block | ||
---|---|---|
| ||
private void doSomething() throws IOException { //... } |
...
Throwing RuntimeException
, Exception
, or General
prevents classes from catching your the intended exception without catching other unintended exceptions as well.
...