Ajit Kumar Dubey
Ajit Kumar Dubey

Reputation: 1563

Why do different Exceptions occur?

I am using the below code. The first line is giving java.lang.NumberFormatException, and the second is giving java.lang.NullPointerException. I'm unable to figure out why.

int intValue =Integer.parseInt(null);
Double double1 = Double.parseDouble(null);

Upvotes: 6

Views: 166

Answers (2)

Jitendra Chandani
Jitendra Chandani

Reputation: 385

This is how both functions are implemented in respective classes.

parseInt method validate the parameter:

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

parseDecimal method first calls trim on the input string parameter:

in = in.trim(); // throws NullPointerException if null

Upvotes: 0

gowtham
gowtham

Reputation: 987

Because thats how they are implemented,

int intValue =Integer.parseInt(null);

If we look the parseInt implementation, they are throwing NumberFormatException if the input string is null

enter image description here

And Double double1 = Double.parseDouble(null);

In parseDouble(String s) method there is another method call i.e FloatingDecimal.readJavaFormatString(s).doubleValue();
In readJavaFormatString(s) method is where exactly NullPointerException is thrown

enter image description here

FloatingDecimal.readJavaFormatString(s) method

enter image description here

Upvotes: 11

Related Questions