...
Noncompliant Code Example
This The isCapitalized()
method in this noncompliant code example accepts a string and returns true
when it consists of a capital letter followed by lowercase letters. To handle corner cases, it checks for various exceptional conditions and throws exceptions when they are likely to disrupt normal operationThe method also throws null 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 violate also rule ERR14-J. Do not catch RuntimeException to handle null
string arguments to the methoddetermine if the RuntimeException
was thrown.
Compliant Solution
This compliant solution throws a specific exception the (NullPointerException
) to denote the particular 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 next call (s.equals("")
) would will throw a NullPointerException
if when s
were is null. However, the explicit null check is good form, because it explicitly indicates the programmer's intent. More complex code may require explicit testing of invariants and appropriate throw statements.
...