Objects.requireNonNull(T obj)而不是null检查并手动抛出IllegalArgumentException? [英] Objects.requireNonNull(T obj) instead of null checks and manually thrown IllegalArgumentException?
问题描述
每当我必须检查方法的给定参数是否为空时,我曾经写过一个空检查并抛出 IllegalArgumentException
如果空检查失败:
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.");
}
但是,通过阅读某些Java 8类的源代码,例如 ArrayList
,我发现Oracle正在使用 Objects.requireNonNull
检查参数是否为空值,然后,如果测试失败,则< a href =https://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html =nofollow noreferrer> NullPointerException
。
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.");
更小,更易读。
假设我控制了系统的整个异常处理,(即使我不应该,有时它是处理这些未经检查的异常的业务的一部分),我应该替换我的 IllegalArgumentException
使用 NullPointerException
并使用 Objects.requireNonNull
而不是编写我自己的null检查和异常抛出?
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?
推荐答案
使用 Objects.requireNonNull(c)
是一种非常优雅的方法来检查元素是否为空。但是有一个有趣的讨论是关于选择 NullPointerException
还是 IllegalArgumentException
- > 有空参数的IllegalArgumentException或NullPointerException?。因此抛出 NullPointerException
是表达引用为空的java方式。
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.
否则,您可以创建自己的方法 requireNotNull()
。这很简单:
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;
}
您可以更改异常 NullPointerException
by IllegalArgumentException
。
and you can change the exception NullPointerException
by IllegalArgumentException
.
这篇关于Objects.requireNonNull(T obj)而不是null检查并手动抛出IllegalArgumentException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!