Reputation: 4615
It's confusing: We all know the words from Doug Lea: "Null sucks". He is right.
Now I there are some approaches to throw exceptions by using googles guava. But what would be the right way now?
1) throwing an NullPointerException
private void foo(Object arg) {
Preconditions.checkNotNull(arg, "arg 'null' not accepted");
}
2) or an IllegalArgumentException
private void foo(Object arg) {
Preconditions.checkArgument(arg!=null, "arg 'null' not accepted");
}
3) or a VerifyException
private void foo(Object arg) {
Verify.verify(arg!=null, "arg 'null' not accepted");
}
I mean, isn't the first approach obsolete cause we don't have a NullPointer access at this time? And why this new third approach.
Could someone lift the fog?
Upvotes: 1
Views: 1059
Reputation: 11920
"Effective Java" seems quite adamantly in favor of throwing a NullPointerException
IllegalArgumentException or NullPointerException for a null parameter?
Upvotes: 1
Reputation: 32969
I agree with Aaron
. My two cents is that since in Java 7 Objects.requireNonNull was added and it throws a NullPointerException
, that is the way I go. To me it seems like the language developers have weighed in on this issue by doing so.
Upvotes: 4
Reputation: 328724
There is no right way. Some people argue NPE since you passed a null pointer. Plus you can directly use Preconditions.checkNotNull()
without any additional checks in code that you have to write (!=null
is another 6-10 key presses, after all, plus people have to read more code to understand what you're doing).
Preconditions.checkArgument()
makes more sense from an API point of view since the method doesn't want null
arguments. Plus you have additional code to write and to read when you're debugging.
Verifify
seems too weak for this for me, after reading the documentation.
Upvotes: 3