...
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. The 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 also violate also rule ERR14-J. Do not catch NullPointerException, RuntimeException, Exception, or Throwable to determine if the RuntimeException https://www.securecoding.cert.org/confluence/pages/editpage.action?pageId=24608774RuntimeException was thrown.![]()
Compliant Solution
...
Note that the null check is redundant; if it were removed, the next call (s.equals("")) will throw a NullPointerException when s is null. However, the explicit null check is a good form, because it explicitly indicates the programmer's intent. More complex code may require explicit testing of invariants and appropriate throw statements.
...
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="6e44be7a8c15a84c-f3e6a6b4-4f224719-8f8598a0-a35f56bcda3a9f5957ac2c60"><ac:plain-text-body><![CDATA[ | [[MITRE 2009 | AA. Bibliography#MITRE 09]] | [CWE ID 397 | http://cwe.mitre.org/data/definitions/397.html] "Declaration of Throws for Generic Exception" | ]]></ac:plain-text-body></ac:structured-macro> |
| CWE ID 537 "Information Exposure Through Java Runtime Error Message" |
...
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="08d064db0135d1ef-2bfde96c-41404a7f-ac7b80aa-fb287255ae1a7fdb44832a3a"><ac:plain-text-body><![CDATA[ | [[Goetz 2004b | AA. Bibliography#Goetz 04b]] |
| ]]></ac:plain-text-body></ac:structured-macro> | |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="37256e2776e3ace9-afeccf71-464a4e79-a3f59071-624c81a1a8494214d367d52b"><ac:plain-text-body><![CDATA[ | [[Tutorials 2008 | AA. Bibliography#Tutorials 08]] | [Unchecked Exceptions — The Controversy | http://java.sun.com/docs/books/tutorial/essential/exceptions/runtime.html] | ]]></ac:plain-text-body></ac:structured-macro> |
...