Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objects.requireNonNull(T obj) instead of null checks and manually thrown IllegalArgumentException?

Tags:

People also ask

What's the point of Objects requireNonNull?

requireNonNull. Checks that the specified object reference is not null and throws a customized NullPointerException if it is. Unlike the method requireNonNull(Object, String) , this method allows creation of the message to be deferred until after the null check is made.

What is Objects nonNull in Java?

The nonNull method is a static method of the Objects class in Java that checks whether the input object reference supplied to it is non-null or not. If the passed object is non-null, then the method returns true. If the passed object is null , then the method returns false.


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?