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

徘徊边缘 提交于 2019-12-21 03:38:40

问题


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?


回答1:


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.




回答2:


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.)



来源:https://stackoverflow.com/questions/31005009/objects-requirenonnullt-obj-instead-of-null-checks-and-manually-thrown-illegal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!