Floating-point numbers can take on three exceptional values, infinity
, -infinity
and NaN
(not-a-number). These values are produced as a result of exceptional or otherwise unresolvable floating-point operations, such as division by zero. These exceptional values can also be obtained directly from user input through methods such as Double.valueOf(String s)
. Failure to detect and handle such exceptional values can result in inconsistent behavior.
The method Double.valueOf(String s)
can return NaN
or an infinite double
, as specified by its contract. Programs should install checks to must ensure that all floating-point inputs (especially those obtained from the user) are free of unexpected exceptional values. The methods Double.isNaN(double d)
and Double.isInfinite(double d)
can be used for this purpose.
NaN
values are particularly problematic because they are unordered. That is, the expression NaN == NaN
always returns false
. (See rule " NUM07-J. Do not attempt comparisons with NaN.")
Noncompliant Code Example
...
Code Block | ||
---|---|---|
| ||
double currentBalance; // User's cash balance void doDeposit(String s){ double val; try { val = Double.valueOf(userInput); } catch(NumberFormatException e) { // Handle input format error } if (Double.isInfinite(val)){ // Handle infinity error } if (Double.isNaN(val)) { // Handle NaN error } if (val >= Double.MAX_VALUE - currentBalance) { // Handle range error } currentBalance += val; } |
Exceptions
FLP08-EX0: Occasionally, NaN
, infinity
, or -infinity
may be acceptable as expected inputs to a program. In such cases, explicit checks might not be necessary. However, such programs must be prepared to handle these exceptional values gracefully and should prevent propagation of the exceptional values to other code that fails to handle exceptional values. The choice to permit input of exceptional values during ordinary operation should be explicitly documented.
...
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="5a090845908a0c8e-3f3b9d80-48a44249-a4c7a432-7dad540a96e70c6f19627860"><ac:plain-text-body><![CDATA[ | [[IEEE 754 | https://www.securecoding.cert.org/confluence/display/seccode/AA.+C+References#AA.CReferences-IEEE7542006 | IEEE 754]] | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="5f168ea58dff5be1-6df4fc10-4e034c64-9353bd90-08bc3318e083bb73aa1c244f"><ac:plain-text-body><![CDATA[ | [[IEEE 1003.1, 2004 | https://www.securecoding.cert.org/confluence/display/seccode/AA.+C+References#AA.CReferences-IEEE1003 | IEEE 1003.1, 2004]] | ]]></ac:plain-text-body></ac:structured-macro> |
...