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

前端 未结 2 702
独厮守ぢ
独厮守ぢ 2021-02-12 22:06

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:



        
2条回答
  •  天命终不由人
    2021-02-12 22:57

    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 requireNonNull(T obj) {
            if (obj == null)
                throw new NullPointerException();
            return obj;
        }
    

    and you can change the exception NullPointerException by IllegalArgumentException.

提交回复
热议问题