在Java中,add()
方法通常用于向集合(如List、Set等)添加元素。在處理異常時(shí),需要考慮以下幾種情況:
add()
操作時(shí),會(huì)拋出此異常。例如,對(duì)于不可修改的集合(如通過Collections.unmodifiableList()
創(chuàng)建的列表),嘗試調(diào)用add()
方法會(huì)導(dǎo)致此異常。List<String> list = Collections.unmodifiableList(Arrays.asList("a", "b", "c"));
try {
list.add("d");
} catch (UnsupportedOperationException e) {
System.err.println("The add operation is not supported by this collection.");
}
Collections.checkedList()
創(chuàng)建的類型檢查列表中添加錯(cuò)誤類型的元素。List<Integer> checkedList = Collections.checkedList(new ArrayList<>(), Integer.class);
try {
checkedList.add("not an integer");
} catch (IllegalArgumentException e) {
System.err.println("The element type is not valid for this collection.");
}
List<String> stringList = new ArrayList<>();
try {
stringList.add(123); // Attempting to add an Integer to a List<String>
} catch (ClassCastException e) {
System.err.println("The element type is not valid for this collection.");
}
List<String> nonNullList = new ArrayList<>();
try {
nonNullList.add(null);
} catch (NullPointerException e) {
System.err.println("This collection does not allow null elements.");
}
add()
方法的索引形式(如list.add(index, element)
)并且指定了超出集合范圍的索引時(shí),會(huì)拋出此異常。List<String> list = new ArrayList<>();
try {
list.add(10, "out of bounds");
} catch (IndexOutOfBoundsException e) {
System.err.println("The specified index is out of bounds.");
}
在處理這些異常時(shí),應(yīng)確保捕獲并適當(dāng)處理它們,以防止程序意外終止。根據(jù)實(shí)際情況,可以選擇記錄錯(cuò)誤、顯示錯(cuò)誤消息或采取其他適當(dāng)?shù)拇胧?/p>