Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do Double.parseDouble(null) and Integer.parseInt(null) throw different exceptions?

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 
like image 464
pho79 Avatar asked May 01 '13 19:05

pho79


People also ask

Can you parseInt null?

If parseInt() is given an empty string or a null value it will also return NaN, rather than converting them to 0. This gives us a mechanism by which we can test values using a combination of parseInt() and isNaN().

What is double parseDouble?

Double parseDouble() method in Java with examples The parseDouble() method of Java Double class is a built in method in Java that returns a new double initialized to the value represented by the specified String, as done by the valueOf method of class Double.

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.

Does Double accept null values?

Java primitive types (such as int , double , or float ) cannot have null values, which you must consider in choosing your result expression and host expression types.


1 Answers

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.

like image 157
Floris Velleman Avatar answered Oct 22 '22 05:10

Floris Velleman