2

The documentation says that there are two types of exceptions for Double.parseDouble() and one for Integer.parseInt(), but it seems inconsistent:

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

Double.parseDouble(null); // throws java.lang.NullPointerException
Basilevs
  • 22,440
  • 15
  • 57
  • 102
Ayyan Alvi
  • 759
  • 2
  • 9
  • 24

2 Answers2

6

You're right: It's inconsistent. Move along, nothing to see here... ;-) The JDK library is very large, has grown over time, and has various inconsistencies. I have to admit this one surprised me enough that I felt the need to double-check your assertion and the actual behavior (in case it differed from the doc): http://ideone.com/18W8W8) But there we go.

As JB points out, one clue to underlying cause of the inconsistency might be that Integer.parseInt was in the JDK from the beginning, but Double.parseDouble was added in 1.2. So perhaps thinking around being more specific about the issue changed between those two times.


SO won't let me post the answer with the link above without code, so:

try {
    Integer.parseInt(null); // throws java.lang.NumberFormatException: null
}
catch (Exception e) {
    System.out.println("Integer: " + e.getClass().getName());
}
try {
    Double.parseDouble(null); // throws java.lang.NullPointerException
}
catch (Exception e) {
    System.out.println("Double: " + e.getClass().getName());
}

Output:

Integer: java.lang.NumberFormatException
Double: java.lang.NullPointerException
Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 2
    Agreed. As an indication, parseDouble() exists since 1.2, whereas parseInt() exists since the beginning. They probably decided that null should be consistently handled by throwing a NullPointerException in 1.1 or 1.2, but couldn't change parseInt() to maintain backward-compatibility. – JB Nizet Nov 08 '14 at 15:37
0

parsed double

public static double parseDouble(String s) throws NumberFormatException
{
    return FloatingDecimal.readJavaFormatString(s).doubleValue();
}

readJavaFormatString will return null, that explains the NullPointerException

ParseInt

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

That's written like that. Not very coherent but there is worse in the JDK.

ToYonos
  • 16,469
  • 2
  • 54
  • 70