java – Objects. Requirenonnull (t obj) instead of null check and throw illegalargumentexception manually?
Whenever I check whether the given parameter of a method is not null, if the null check fails, I use it to write a null check and throw an illegalargumentexception:
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 that oracle was using objects Require nonnull to check a null parameter, and then throw a NullPointerException exception if the test fails
In this way, early code fragments should adopt this method:
Objects.requireNonNull(user,"User can't be null.");
Smaller, more readable
Assuming I control the whole exception handling of the system (even if I shouldn't, sometimes it's part of the business dealing with these unchecked exceptions), I should replace my illegalargumentexceptions with NullPointerException and use objects Require nonnull instead of writing my own null checks and exception throws?
Solution
Using objects Requirenonnull (c) is a very elegant way to check whether an element is not empty However, there is an interesting discussion about choosing NullPointerException or illegalargumentexception – > so throwing NullPointerException is a Java way to indicate that the reference is empty
Otherwise, you can use your own method requirenotnull() It's simple:
public static <T> T requireNonNull(T obj) { if (obj == null) throw new NullPointerException(); return obj; }
And you can change the exception NullPointerException through illegalargumentexception