我有一个简单的setter方法的属性和空是不适合这个特定的属性。在这种情况下,我总是被撕裂:我应该抛出一个IllegalArgumentException,还是一个NullPointerException?从javadocs来看,两者都很合适。是否存在某种公认的标准?或者这只是其中一件事,你应该做任何你喜欢做的事情,两种都是正确的?


当前回答

如果它是一个setter方法,并且null被传递给它,我认为抛出一个IllegalArgumentException会更有意义。NullPointerException似乎在尝试实际使用null的情况下更有意义。

如果你在使用它,它是空的,NullPointer。如果它被传入并且它为空,则为非法参数。

其他回答

以上两个例外的链接定义如下 IllegalArgumentException:抛出该异常,表示方法被传递了一个非法或不适当的参数。 NullPointerException:当应用程序试图在需要对象的情况下使用null时抛出。

这里最大的区别是IllegalArgumentException应该在检查方法的参数是否有效时使用。当一个对象被“使用”为空时,就应该使用NullPointerException。

我希望这能帮助你正确看待这两者。

如果您选择抛出NPE,并且在方法中使用参数,显式检查null可能是多余的和昂贵的。我想VM已经为你做了。

抛出一个排除空参数的异常(无论是NullPointerException还是自定义类型)使得自动化空测试更加可靠。这种自动化测试可以通过反射和一组默认值来完成,就像在Guava的NullPointerTester中一样。例如,NullPointerTester将尝试调用以下方法…

Foo(String string, List<?> list) {
  checkArgument(string.length() > 0);
  // missing null check for list!
  this.string = string;
  this.list = list;
}

...with two lists of arguments: "", null and null, ImmutableList.of(). It would test that each of these calls throws the expected NullPointerException. For this implementation, passing a null list does not produce NullPointerException. It does, however, happen to produce an IllegalArgumentException because NullPointerTester happens to use a default string of "". If NullPointerTester expects only NullPointerException for null values, it catches the bug. If it expects IllegalArgumentException, it misses it.

二分法……它们不重叠吗?只有整体中不重叠的部分才能构成二分法。在我看来:

throw new IllegalArgumentException(new NullPointerException(NULL_ARGUMENT_IN_METHOD_BAD_BOY_BAD));

公认的做法是使用IllegalArgumentException(字符串消息)来声明一个参数是无效的,并给出尽可能多的细节…所以说,一个参数被发现是空的,而异常是非空的,你会这样做:

if( variable == null )
    throw new IllegalArgumentException("The object 'variable' cannot be null");

你几乎没有理由隐式地使用“NullPointerException”。NullPointerException是当您试图在空引用(如toString())上执行代码时由Java虚拟机抛出的异常。