【发布时间】:2014-11-10 11:28:20
【问题描述】:
我在下面有一些代码,在一些非常模糊的情况下,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 is -1,则ArrayList class will throw an IndexOutOfBounds Exception within the sublistRangeCheck method。
我的查询:
我应该如何在我们的代码中最好地处理这个异常?我应该用 try catch 包围它,打印堆栈跟踪并记录一些附加信息以进行调试吗?我是否应该在执行 for 循环之前防御性地检查 fromPeriod 是否 >= 0,如果没有记录一些信息?
您将如何/在您的代码中处理此类场景的最佳做法是什么?
提前致谢。
【问题讨论】:
-
如果 fromIndex 变为 -1,你想要做什么默认值?您应该默认为 0 还是从那里返回等?
标签: java exception arraylist error-handling indexoutofboundsexception