Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ccccff
double i = Double.MIN_VALUE;
double j = Double.MAX_VALUE;
if ((i < Float.MIN_VALUE) || (i > Float.MAX_VALUE) ||
    (j < Float.MIN_VALUE) || (j > Float.MAX_VALUE)) {
  throw new ArithmeticException ("Value is out of range");    
}

float b = (float) i;
float c = (float) j;
//other operations

Exceptions

EXP13-EX1: Since Java's narrowing conventions conversions are both well-defined , they may be intentinally applied by programmers, and so their outputs would be expected and perfectly reasonable. Code that accounts for potential truncation, and documents this, is concisered a valid exception to this rule.and portable; knowledgable programmers can intentionally apply such conversions in contexts where their output is both expected and reasonable. Consequently, narrowing conversions are permitted when the code contains comments that document both the use of narrowing conversions and that the potential for truncation has been anticipated. A suitable comment might read: "//Deliberate narrowing cast of i; possible truncation OK"

Risk Assessment

Casting a numeric value to a narrower type can result in information loss related to the sign and magnitude of the numeric value. Consequently, data can be misrepresented or interpreted incorrectly.

...