IndexOutOfBoundsException发生在访问集合或数组越界时,应优先通过size()和索引检查预防,如index >= 0 && index在Java中操作集合时,IndexOutOfBoundsException 是最常见的运行时异常之一。它通常发生在访问集合(如 ArrayList、LinkedList、数组等)中不存在的索引位置时。为了编写健壮的程序,必须学会如何安全地处理这类异常。
理解IndexOutOfBoundsException
当尝试访问集合或数组中超出有效范围的索引时,Java会抛出 IndexOutOfBoundsException。常见子类包括:
- ArrayIndexOutOfBoundsException:数组索引越界
- StringIndexOutOfBoundsException:字符串索引越界
例如:
Listlist = new ArrayList<>(); list.add("A"); String item = list.get(5); // 抛出 IndexOutOfBoundsException 预防优于捕获:避免异常发生
最安全的方式是在访问前检查索引有效性,而不是依赖 try-catch 捕获异常。
- 始终使用 list.size() 获取集合长度
- 访问前判断索引是否满足:index >= 0 && index
示例:
Listlist = Arrays.asList("apple", "banana", "cherry"); int index = 5; if (index >= 0 && index < list.size()) { System.out.println(list.get(index)); } else { System.out.println("索引无效:" + index); } 使用 try-catch 安全捕获异常
在无法预知索引合法性时,可用 try-catch 包裹高风险操作。
try { String value = list.get(index); System.out.println("值:" + value); } catch (IndexOutOfBoundsException e) { System.err.println("索引越界:" + index); // 可记录日志或返回默认值 }
注意:不要用异常控制正常流程。异常处理开销大,应仅用于意外情况。
封装安全访问工具方法
可创建通用方法避免重复判断逻辑。
public staticT safeGet(List list, int index) { if (list == null || index < 0 || index >= list.size()) { return null; } return list.get(index); } 调用时无需担心异常:
String result = safeGet(myList, 10); if (result != null) { // 安全使用 }基本上就这些。关键是优先做边界检查,把异常当作最后防线。

BoundsException e) {
System.err.println("索引越界:" + index);
// 可记录日志或返回默认值
}







