98

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
3
  • 2
    @Aquillo: There is double primitive docs.oracle.com/javase/tutorial/java/nutsandbolts/… Commented May 1, 2013 at 19:19
  • 2
    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. Commented May 1, 2013 at 19:26
  • I have checked that they throw the sameNumberFormatException. Commented Feb 26, 2016 at 2:27

2 Answers 2

73

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
Amusingly, the comment said that this functionality was "very old" at the time, and that was 15 years ago now.
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.)
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.