在 java 的 get() 方法中捕获 IndexOutOfBoundsException

catch IndexOutOfBoundsException in get() method in java

如果有人能帮助我理解为什么我的代码不能按应有的方式工作,我将不胜感激:

我想在 getter 方法中被测试的索引(在主 class 中)超出我的 ArrayList 的范围时捕获异常。

它应该表现得像:如果索引(使用 8 进行测试)超出 ArrayList(长度为 5)的范围,则程序将不会获取任何值并打印出语句 Will Skip,并继续移动到下一行。如果索引没有越界,return ArrayList 中的值。

只有当 Catch() 中有 "return" 值时,我下面的内容才有效。我知道这是因为 getter 要求 return 加倍。但我不知道如何解决这个问题以按照上述方式行事。非常感谢!

用于测试的主驱动程序class:

TestValue object = new TestValue();

System.out.println("The value is " + object.getListValue(8));

...other methods like print values, set new values etc.

测试值class:

public double getListValue(int index) { 

     try {  
        listValue.get(index);
        while (index <0 || index >= listValue.size()) { 
        }
    }
    catch (IndexOutOfBoundsException e) {
        System.out.println(e.getMessage());
        System.out.println("Can't get value. Will skip this request. ");
        return listValue.get(0); // I don't want to return any values
    }
    return listValue.get(index);
}

这是因为您的方法定义是public double, 你必须 return a double 除非你抛出异常。 如果你真的不想 return 一个值,你可以 return 0.0.