Double.parseDouble accepts special non-finite values and can overflow to Infinity, so a numeric measurement parser should validate finiteness explicitly.
Java Double.isFinite: reject Infinity and NaN at input boundaries
Reject invalid measurements early
A sensor API that expects a physical reading should not accept NaN or Infinity as an ordinary quantity. A huge exponent such as 1e400 parses to Infinity rather than throwing a range error. Double.isFinite catches both that result and explicit NaN input.
The fixture accepts 47.5 and rejects two non-finite strings. NaN key behavior explains why passing these values onward can affect collection semantics.
Separate finiteness from range
A finite value can still exceed the sensor's allowed physical range. Check both conditions at the request boundary. For exact decimal money, use BigDecimal with its own scale and precision policy rather than double.
Working program
public class SensorReadingGate {
static double parse(String raw) {
double reading = Double.parseDouble(raw);
if (!Double.isFinite(reading)) throw new IllegalArgumentException("non-finite reading");
return reading;
}
public static void main(String[] args) {
System.out.println(parse("47.5"));
for (String raw : new String[] {"1e400", "NaN"}) {
try { parse(raw); }
catch (IllegalArgumentException rejected) { System.out.println(rejected.getMessage()); }
}
}
}Output
47.5
non-finite reading
non-finite readingCost and ownership
Parsing work grows with input length, so cap the field size before conversion. The finite check is constant work and does not replace domain range validation or an exact-decimal policy.
Common Mistakes
- Do not assume parseDouble rejects an overflowing exponent.
- Do not let NaN pass a normal measurement validation path.
- Do not use finiteness as the only range check.
Read next
Java Double NaN and signed zero: primitive and wrapper comparisons differ, floating sum order, Java BigDecimal: decimal amounts and explicit rounding, Java DecimalFormat: reject trailing input and pin the locale.
