Java 我应该如何处理这个IndexOutOfBounds异常?

Java 我应该如何处理这个IndexOutOfBounds异常?,java,exception,arraylist,error-handling,indexoutofboundsexception,Java,Exception,Arraylist,Error Handling,Indexoutofboundsexception,下面是一些代码,在一些非常模糊的情况下,fromIndex变量设置为-1: int fromIndex = 0; if (newCurrentPeriod != null) { // Guard in case we are rolling back to before the start of the event. fromIndex = allPeriods.indexOf(newCurrentPeriod); } for (Period resetPeriod : al

下面是一些代码,在一些非常模糊的情况下,fromIndex变量设置为-1:

int fromIndex = 0;
if (newCurrentPeriod != null) {
    // Guard in case we are rolling back to before the start of the event.
    fromIndex = allPeriods.indexOf(newCurrentPeriod);
}  
for (Period resetPeriod : allPeriods.subList(fromIndex, toIndex)) {
    ...
}
当前,如果
fromIndex为-1
,则
ArrayList类将在sublistRangeCheck方法中引发IndexOutOfBounds异常

我的查询:

我应该如何在代码中最好地处理此异常?我是否应该用try-catch来包围它,打印堆栈跟踪并记录一些额外的信息以进行调试?在执行for循环之前,我是否应该防御性地检查fromPeriod是否大于等于0,如果不记录一些信息

在您的代码中,您如何/什么是处理此类场景的最佳实践


提前感谢。

理想情况下,捕获IndexOutOfBounds(运行时异常)不是一个好做法

运行时异常是一种可能由程序员避免的异常

运行时异常只应在完整操作结束时捕获,以便向用户显示发生错误的消息

此外,运行时异常不会在编译时被识别,如果您可以通过一个小检查来识别异常的概率(如NullPointer的null检查、IndexOutofBounds的索引检查),这是减少JVM开销的最佳实践


添加对fromIndex==-1的检查将是更好的方法,并记录迭代发生的详细信息。

对于那些模糊的场景,我更希望在进入方法之前进行检查

int fromIndex = 0;
    if (newCurrentPeriod != null) {
        // Guard in case we are rolling back to before the start of the event.
        fromIndex = allPeriods.indexOf(newCurrentPeriod);
    }  
if (fromIndex>=0)
    for (Period resetPeriod : allPeriods.subList(fromIndex, toIndex)) {
        ...
    }
else syso("print something");

indexOf是列表界面的一部分,文档中的定义是:

返回:中指定元素第一次出现的索引 此列表,如果此列表不包含元素,则为-1

更确切地说:

更正式地说,返回最高的索引i,这样(o==null? get(i)==null:o.equals(get(i)),如果没有这样的索引,则为-1

这意味着当索引为-1时,列表中不存在要查找的对象

您是否在对象中实现了自定义的“equals”方法?如果没有,列表将显示。正在使用对象的实例id来匹配它们,这意味着包含相同数据的该对象的两个实例仍然不同,因为它们不是相同的实例

因此,如果您确定要查找的对象在列表中,请检查“equals”方法或实现一个基于输入而不是实例比较对象的方法

如果搜索的对象可能不在列表中,那么您只需处理不需要获取子列表的情况

if (formIndex >= 0) {
        for (Period resetPeriod : allPeriods.subList(fromIndex, toIndex)) {
            ...
        }
}

如果fromIndex变为-1,您要执行的默认操作是什么?你应该默认为0还是从那里返回等?你能详细说明一下为什么这是一种不好的做法吗?