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

前端 未结 2 654
独厮守ぢ
独厮守ぢ 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条回答
  •  梦毁少年i
    2021-02-12 22:44

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

提交回复
热议问题