Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: minor

...

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
bgColor#ffcccc
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=24608774RuntimeExceptionImage Added 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="24f9628e47175434-0d7dbc3a-40854c32-90198c44-7de81909e72555863e039f48"><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="0e6ac0ef28bb6cc7-bbc8b17c-4d154a7d-842a957b-1c431fce660c9f71c42f0a12"><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="eb0362fba5c05048-b9f15328-4907458f-89ed8047-d5a2ee98af765708404b96f2"><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>

...