96

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
pho79
  • 1,755
  • 1
  • 15
  • 27
  • 2
    @Aquillo: There is `double` primitive http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html – nhahtdh May 01 '13 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. – NilsH May 01 '13 at 19:26
  • I have checked that they throw the sameNumberFormatException. – twlkyao Feb 26 '16 at 02:27

2 Answers2

71

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.

Floris Velleman
  • 4,848
  • 4
  • 29
  • 46
  • 2
    Related and interesting bug report: http://bugs.sun.com/view_bug.do?bug_id=6463998 Seems like in Java 6, parse method from Double/Float class throws NPE. – nhahtdh May 01 '13 at 19:39
  • 2
    Amusingly, the comment said that this functionality was "very old" *at the time,* and that was 15 years ago now. – Southpaw Hare Nov 30 '17 at 18:40
  • 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.) – Stephen C Jan 10 '19 at 12:50
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.

durron597
  • 31,968
  • 17
  • 99
  • 158