19

Whenever I had to check if the given parameters to a method are not null, I used to write a null check and throw a IllegalArgumentException if the null check fails:

    if (user == null) {
        throw new IllegalArgumentException("User can't be null.");
    }

However, by reading the source code of some Java 8 classes such as ArrayList, I found out that Oracle are using Objects.requireNonNull to check a parameter against a null value, and then, if the test fails, a NullPointerException is thrown.

This way, the earlier code snippet should look like this by adopting this approach:

Objects.requireNonNull(user, "User can't be null.");

Smaller and more readable.

Assuming that I have control of the whole exception handling of the system, (even that I shouldn't, sometimes it is part of the business to handle these unchecked exceptions), should I replace my IllegalArgumentException with NullPointerException and use Objects.requireNonNull instead of writing my own null checking and exception throwing?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Bruno Gasparotto
  • 671
  • 12
  • 31
  • 15
    We are doing so in the JDK for new code, and adapting old code opportunistically. And its quite possible in the future that the JVM will eventually intrinsify Objects.requireNonNull, which is another reason to prefer it. The "should I use NPE or IAE" debate is mostly a rathole; both positions are defensible, and most effort spent arguing between them is wasted. – Brian Goetz Jun 23 '15 at 14:46
  • 3
    When Brian Goetz says he's doing it one way, chances are that's the way you'll want to do it ;-). – Daniel Jun 23 '15 at 21:16
  • @BrianGoetz, this way I'll prefer to adopt the `NullPointerException` when these null check fails. Joshua already stated in his book the preference to `NPE` over `IAE`, and also, by reading what you said about the future of the JDK, I think I have enough evidence to got that way. By the way, @OSryx answer stills valid to implement another kind of parameter checking. – Bruno Gasparotto Jun 24 '15 at 12:59
  • 2
    @Daniel I wish this were true, but with a codebase this big with 20 years history and hundreds of chefs in the kitchen, inconsistencies are inevitable. But, does it matter? These are not exceptions designed to be caught by the caller. It is more important that you do _any argument checking at all_. I fear we spend more effort arguing over the best way to do argument checking, more than we spend actually doing it. – Brian Goetz Jun 24 '15 at 15:35
  • 6
    BTW, the API of `Objects.requireNonNull()` allows you to use it in a chained `this()` or `super()` call too: `super(requireNonNull(x))`. – Brian Goetz Jun 24 '15 at 15:36

2 Answers2

14

Using Objects.requireNonNull(c) is a very elegant way to check if the element is not null. But there is an interesting discussion about whether choosing NullPointerException or IllegalArgumentException --> IllegalArgumentException or NullPointerException for a null parameter?. So throwing NullPointerException is the java way to express that a reference is null.

Otherwise, you can make your own method requireNotNull(). It is simple :

 public static <T> T requireNonNull(T obj) {
        if (obj == null)
            throw new NullPointerException();
        return obj;
    }

and you can change the exception NullPointerException by IllegalArgumentException.

Community
  • 1
  • 1
  • The top rated answers of the said discussion made a point along with the answers here. `IllegalArgumentException` looks more appropriate, so I can still use then combined with my "own version" of `Objects.requireNotNull`, which throws the exception I want. – Bruno Gasparotto Jun 23 '15 at 14:34
  • 4
    be careful, sometime the top rated answer is maybe the oldest one ;) –  Jun 23 '15 at 14:35
  • 2
    You are right. by searching a little more, I've found out that even Joshua Bloch defends the use of `NullPointerException` instead of `IllegalArgumentException`, I opened his book to make sure. Now I understand why it's is sometimes called as a "holy war" question, both approaches have good points. However, this discussion is not the idea of this topic, so I might accept your answer very soon. – Bruno Gasparotto Jun 23 '15 at 16:04
  • If you are going to roll your own, you might want to add \@Nullable to the parameter and \@NotNull to the return type. – cquezel Jan 19 '18 at 19:33
7

There is a discussion of what kind of exception should be thrown when a method receives a null value it doesn't expect. Some people argue for NullPointerException, some people argue for IllegalArgumentException. The JDK way seems to be to throw NullPointerException in such cases, which is why the Objects.requireNonNull throws it.

But I wouldn't modify existing code just because of this method, although you might want to consider using Objects.requireNonNull in new code. (Using it in generally makes code more readable than to check for null and throw an exception manually.)

Hoopje
  • 12,677
  • 8
  • 34
  • 50
  • 2
    Where I work, we created our own `Ensure.notNull(Object val, String msg)` which does basically the same thing. However it throws `IllegalArgumentException` not `NullPointerException` for the reasons indicated by Hoopje. We've found this preferable as it makes asserted non-null arguments clearly distinct from accidental NPXs. Although I haven't done it in our code base yet, I've considering creating a new `NullArgumentException` (extends `IllegalArgumentException`) and having it throw that. – Paul Jun 23 '15 at 14:20
  • 1
    This "*We've found this preferable as it makes asserted non-null arguments clearly distinct from accidental NPXs.*" is a bit moot - when you get a NPE you also have a line number so in this specific case you can see that the argument is null - and `Objects.requireNonNull` allows you to provide a specific error message if you want. – assylias Jun 23 '15 at 16:09