在Java中處理數(shù)組異??梢圆捎靡韵录记桑?/p>
int[] arr = {1, 2, 3};
try {
int value = arr[3]; // 數(shù)組越界異常
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("數(shù)組越界異常發(fā)生:" + e.getMessage());
}
int[] arr = null;
try {
int value = arr[0]; // 空指針異常
} catch (NullPointerException e) {
System.out.println("空指針異常發(fā)生:" + e.getMessage());
}
public void getValueFromArray(int[] arr, int index) throws ArrayIndexOutOfBoundsException {
if (index >= arr.length) {
throw new ArrayIndexOutOfBoundsException("數(shù)組越界異常");
}
int value = arr[index];
}
int[] arr = {1, 2, 3};
int index = 3;
assert index >= 0 && index < arr.length : "數(shù)組越界異常";
int value = arr[index];
這些技巧可以幫助您更好地處理數(shù)組異常,提高程序的穩(wěn)定性和可靠性。