Philipp Sander
Philipp Sander

Reputation: 10249

Throw new NullPointerException VS invoking method on null object

I want to test my application and check if it handles NullPointerExceptions correctly.

I have two ideas how to do this:

throw new NullPointerException();

and:

((Object) null).hashCode();

They both produce the identical stacktrace.

The second one is "more real" to me, because this is what would happen in my real code.

Is there any difference between those two statements? Which should i use?

Upvotes: 0

Views: 477

Answers (3)

Suresh Atta
Suresh Atta

Reputation: 121998

Use directly

throw new NullPointerException();

Because,JRE throws NullPointerException when

  • Calling the instance method of a null object.

  • Accessing or modifying the field of a null object.

  • Taking the length of null as if it were an array.

  • Accessing or modifying the slots of null as if it were an array.

  • Throwing null as if it were a Throwable value.

When you do this

((Object) null).hashCode();

You met the first condition and JRE throws the NPE.

Finally You are increasing one more step. That's it. No Difference.

Upvotes: 2

Daniel
Daniel

Reputation: 36710

Both lines of code throw an identical exception, as documented. Unless you want to test the JRE / Java (which is totally unnecessary) there is no difference between both lines in terms of a test strategy.

Upvotes: 0

René Link
René Link

Reputation: 51393

Use

throw new NullPointerException();

because you want to test if your application hanldes a NullPointerException correctly.

Upvotes: 2

Related Questions