This code:
Double.parseDouble("ABC")
throws a NumberFormatException
.
Why is it wrong to expect a Double.NaN
(NaN is literally Not-A-Number).
A working example is this:
public static void main(String[] args) {
System.out.println("Is ABC a number? " + Double.isNaN(Double.parseDouble("ABC"));
}
I expect Is ABC not a number? true
as output.
Why must this be an Exception?
6
NaN has a very specific meaning as the result of an undefined numerical operation such as division by zero or taking the square root of a negative number (within the realm of real numbers). It’s not an appropriate return value from code that parses a floating point number.
Code like that should signal an error when it comes across text that can’t be parsed as a number.
Also, as others have mentioned, it’s a consistency issue. Only floating point values even have a NaN. Integer and boolean types don’t. parseX() should behave the same way in all cases where possible.
This is called the principle of least surprise. That is, design things in the most consistent way possible to avoid surprising others using your APIs.
This lets you easily detect the cases where the input is completely nonsensical. You can parse the string “NaN” and get NaN, so if the user wanted to give you NaN, he could type that. The fact that you received “ABC” means they weren’t even trying to enter a double
at all.
4
In addition to the good answer by @Doval, throwing a NumberFormatException
is more general: it works for similar methods like Integer.parseInt(). There is no NaN equivalent for ints, shorts, etc.
So, throwing a NumberFormatException is both more specific/informative than returning NaN, it is also more generalizable.
That’s truly a win-win!
1