1

So im preparing for interviews and in one of Gayle Laakmans career Cup videos a guy is writing a simple method that takes in an array and does something with it. She mentions his lack of error checking so he adds in this line like so:

public int max(int[] array) {
    if (array == null)
        throw new NullPointerException();

    //method body

}

Is it correct to manually throw a NPE exception like this, this exception will get thrown anyway in the method body as it will use the array reference at some point.

A possible advantage to this i can see is that it separates input invalidation from the method logic being invalid and somehow creating a null reference. Otherwise it is a little confusing and maybe IllegalArgumentException would work better?

4

2 回答 2

3

进入方法后立即抛出没有什么问题,NullPointerException而不是在一些处理完成后等待检测它。如果该方法将失败,它也可能很快失败。

Joshua Bloch 的Effective JavaNullPointerException建议在这种情况下扔掉IllegalArgumentException(第 60 条:支持使用标准异常)。

如果调用者传入null了一些禁止 null 值的参数,则约定将NullPointerException其抛出而不是IllegalArgumentException.

IllegalArgumentException当传入非法的非空值时应该抛出。

于 2013-04-12T18:22:44.010 回答
1

还可以看看 java 自己的实用程序类java.util.Objects

public static <T> T requireNonNull(T obj,
               String message)

检查指定的对象引用是否不为空,如果是则抛出自定义的 NullPointerException。该方法主要用于在具有多个参数的方法和构造函数中进行参数验证,如下所示:

 public Foo(Bar bar, Baz baz) {
     this.bar = Objects.requireNonNull(bar, "bar must not be null");
     this.baz = Objects.requireNonNull(baz, "baz must not be null");
 }
  • 类型参数:
    T - 引用的类型

  • 参数:
    obj - 检查无效性的对象引用
    message - 在引发 NullPointerException 的情况下使用的详细消息

  • 返回:如果不为空,则 返回
    obj

  • 抛出:
    NullPointerException - 如果 obj 为 null

来自https://docs.oracle.com/javase/7/docs/api/java/util/Objects.html

结论

您是否使用此实用程序类是另一个问题,但它明确表明,Java 语言背后的团队打算将NullPointerException用于这些目的。

于 2017-03-22T06:40:55.247 回答