Why do Double.parseDouble(null) and Integer.parseInt(null) throw different exceptions?
Asked Answered
S

2

97

Why do Double.parseDouble(null) and Integer.parseInt(null) throw different exceptions?

Is this a historical accident or intentional? The documentation clearly states two types of exceptions for Double.parseDouble(...) and one for Integer.parseInt(), but it seems inconsistent:

Integer.parseInt(null); // throws java.lang.NumberFormatException: null

However

Double.parseDouble(null); // throws java.lang.NullPointerException
Selfinterest answered 1/5, 2013 at 19:16 Comment(3)
@Aquillo: There is double primitive docs.oracle.com/javase/tutorial/java/nutsandbolts/…Hermeneutics
Checking the source code of the respective methods, it seems like just an inconsistency. parseDouble does not do a null check, and just throws an NPE when it is encountered, but in parseInt, then input string is checked for null. I can't see any good reason why they should behave different.Lateritious
I have checked that they throw the sameNumberFormatException.Channelize
S
72

It is reasonable to expect the same exceptions to be thrown for null; however, these api's are very old and may not be able to be changed at this point.

And:

Since the exception behavior is long-standing and specified in the JavaDoc, it is impractical to change either method's behavior at this time. Closing as will not fix.

As taken from: Bug Report: Integer.parseInt() and Double.parseDouble() throw different exceptions on null.

Like others have stated: It's likely made by different authors.

Shamrao answered 1/5, 2013 at 19:30 Comment(3)
Related and interesting bug report: bugs.sun.com/view_bug.do?bug_id=6463998 Seems like in Java 6, parse method from Double/Float class throws NPE.Hermeneutics
Amusingly, the comment said that this functionality was "very old" at the time, and that was 15 years ago now.Hope
This inconsistency most likely originates in Java 1.0. Unfortunately, it would be difficult to verify that. I don't think Java 1.0 is available for download, and you would need a Windows 95 / NT box to run it. Or an ancient SPARC machine.)Anal
P
59

Note: everything in this post is in the source of Java7-b147

Double.parseDouble() goes into a Sun library (in sun.misc.FloatingDecimal) the first important thing that happens is:

in = in.trim(); // don't fool around with white space.
                // throws NullPointerException if null

Integer.parseInt() is done manually in the Integer class. The first important thing that happens is:

if (s == null) {
    throw new NumberFormatException("null");
}

I would guess there are two different authors.

Precatory answered 1/5, 2013 at 19:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.