Stumbled across this while checking my error handling code. When you call Integer.parseInt(null)
Java throws a NumberFormatException whereas Float.parseFloat(null)
throws a NullPointerException. See also the documentation for Float and Integer
Is there a specific technical or design reason for this difference, or is it just a historical quirk?
The NumberFormatException occurs when an attempt is made to convert a string with improper format into a numeric value. That means, when it is not possible to convert a string in any numeric type (float, int, etc), this exception is thrown. It is a Runtime Exception (Unchecked Exception) in Java.
ParseInt can lead to complex problems—it throws a NumberFormatException on invalid data. Many exceptions will lead to slower program performance.
NumberFormatException: For input string: "null" is specifically saying that the String you receive for parsing is not numeric and it's true, "null" is not numeric. Many Java methods which convert String to numeric type like Integer. parseInt() which convert String to int, Double.
It is definitely a historical artifact.
This inconsistency and related documentation issues have been raised as a Java Bug a few times over the years. For example:
In the earliest of these, the Sun engineers who were assigned to deal with the issue wrote this:
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.
Will consider for Tiger. [That was Java 5.0]
2002-12-03
Then a year later:
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.
2003-10-21
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With