Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Float.parseFloat() throw both NumberFormatException and NullPointerException but Integer.parseInt() only throws NumberFormatException?

Tags:

java

exception

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?

like image 501
ZeitPolizei Avatar asked Apr 08 '19 07:04

ZeitPolizei


People also ask

What is NumberFormatException in ParseInt?

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.

Can ParseInt produce exception?

ParseInt can lead to complex problems—it throws a NumberFormatException on invalid data. Many exceptions will lead to slower program performance.

What is java lang NumberFormatException null?

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.


1 Answers

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:

  • https://bugs.openjdk.java.net/browse/JDK-6463998
  • https://bugs.openjdk.java.net/browse/JDK-7133642
  • https://bugs.openjdk.java.net/browse/JDK-4787924

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

like image 53
Stephen C Avatar answered Sep 22 '22 08:09

Stephen C