0

我想在一个期望只有一个元素的列表的方法中抛出一个异常,如果列表有多个元素,我想抛出一个异常。我正在尝试确定是否有适当的现有 Java 异常可以针对这种情况抛出。我试着在这里查看列表,但没有看到任何正确的跳出。

在这种情况下,我正在调用对象的方法,期望该方法将所述列表引用为对象的属性。所以我实际上没有传递数组,也没有传递索引作为参数。

(为澄清而编辑)

4

5 回答 5

4

由于您试图暗示给定的输入不是有效的输入,因此您应该使用IllegalArgumentException一条说明相同原因的消息。

throw new IllegalArgumentException("Input specified has more elements then expected");

否则,您可以拥有自己的Exception唯一定义条件的。

虽然我不知何故觉得它的元素数量是异常的原因,你甚至可以使用IndexOutOfBoundsException这在给定的场景中是有意义的。

throw new IndexOutOfBoundsException("Expected size is 1, submitted input has size " + list.size());

编辑:根据评论

鉴于该列表不是方法调用的一部分,而是属于其方法被调用的对象,在这种情况下list.size() > 1表示对象未处于正确状态,并且带有适当错误消息的自定义版本IllegalStateExceptionIllegalStateException本身将更合适。

于 2012-05-21T17:29:48.023 回答
3

您可以创建自己的异常并抛出它。

public MyException extends Exception {
}

if(list.size() > 1) {
    throw new MyException("Expected only 1 element, found: " + list.size());
}
于 2012-05-21T17:29:02.320 回答
1

如果列表是您正在调用该方法的对象的字段,那么您可以说具有错误大小列表的对象处于错误状态,因此IllegalStateException是合适的。

但实际上,您应该用标量字段 ( List<Foo>become Foo) 替换列表,这样就不会出现这种情况。

于 2012-05-21T17:39:27.770 回答
0

您可以像这样在方法中抛出错误

public void someMethod(List<MyClass> myList) throws NullPointerException, IllegalArgumentException {
    if (myList == null)
        throw new NullPointerException("myList parameter can't be null");
    if (myList.size() > 1) {
        throw new IllegalArgumentException("myList parameter must contain only 1 parameter");
    }
    //your code here...
}

最好在属性文件中设置错误消息,这样您只需要更改配置即可显示新消息,无需通过修改代码来重写错误消息。

于 2012-05-21T17:31:05.170 回答
0

我不确定我是否理解用例,所以这个答案可能不正确,但我建议使用 AssertionError

List < T > answers ; // expection a list of size one
assert 1 == list . size ( ) : "The programmer expects that there will be one and only one answer"
/*
In development:  assertions enabled,
 If there are zero answers, the program will crash on the assertion.
 If there are multiple answers, the program will crash on the assertion.
 Only if there is exactly one answer will it proceed to the below line (and work correctly).
In production:  assertions disbled,
 If there are zero answers, the program will throw a RuntimeException on the below line.
 If there are multiple answers, the program will proceed to the below line (and appear to work).
 If there is only one answer, the program will proceed to the below line and wok correctly.
*/
T answer = answers . get ( 0 ) ;

这种方法优于使用ifswitch

  1. 一些代码覆盖工具会希望您为分支编写单元测试。
  2. 分支增加了圈复杂度。
  3. 评估仅在开发期间执行
于 2012-05-21T17:56:29.930 回答