package Xiaojian.java.coding.day131;
public class MainDemo {
public static void main(String[] args) {
int[] a = {1,3,5,8,7};
//Exception in thread "main" java.lang.IndexOutOfBoundsException: 数组越界
//int e = GetElement(a,5);
//Exception in thread "main" java.lang.NullPointerException: 数组不能为空!
//int e = GetElement(null,2);
//正确写法
int e = GetElement(a,3);
System.out.println(e);
}
public static int GetElement(int[] a,int index) {
if(a == null) {
throw new NullPointerException("数组不能为空!");
}
if(index<0 || index>a.length-1){
throw new IndexOutOfBoundsException("数组越界");
}
return a[index];
}
}
异常处理throw
最新推荐文章于 2022-05-21 15:50:33 发布