package chapter10;
public class Chapter1002 {
public static void main(String[] args) {
int[] arr = {1,2,3};
//int[] arr = null;
int index = 4;
int decimal = getMember(arr,index);
System.out.println(arr[index]);
}
//对方法传递过来的参数进行合法校验
public static int getMember(int[] arr, int index) {
if (arr == null) {
throw new NullPointerException("空指针异常");
}
if (index < 0 || index > arr.length - 1) {
throw new ArrayIndexOutOfBoundsException("超出数组使用范围");
}
int decimal = arr[index];
return decimal;
}
}
运行结果:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 超出数组使用范围
at chapter10.Chapter1002.getMember(Chapter1002.java:16)
at chapter10.Chapter1002.main(Chapter1002.java:8)