@momo
1.throw
作用:thorw关键字可以在指定的方法中抛出指定的异常
使用格式:
throw newxxxException(“异常产生的原因”);
注意:
1.throw关键字必须写在方法的内部
2.throw关键字后边new的对象必须是Exception或者Exception的子类对象
3.throw关键字抛出指定的异常,我们就必须处理这个异常对象
throw关键字后边创建的是RuntimeExceptoin或者是RuntimeExceptoin的子类对象我们可以不处理,默认交给JVM处理(打印异常对象,中断程序)
throw关键字后边创建的是编译异常(写代码时候报错),我们就必须处理这个异常要么throws,要么try…catch
代码:
public class DemoThrow {
public static void main(String[] args) {
//int []arr =null;
int []arr = new int [3];
int e = getElement(arr,4);
System.out.println(e);
}
public static int getElement(int []arr,int index) {
/*
对传递过来的数组进行合法性验证
如果数组的值为null,就抛出空指针异常,告知传递者传递的数组值为null
*/
if(arr==null) {
throw new NullPointerException("传递的数组值为null");
}
if(index<0 ||index>arr.length-1){
throw new ArrayIndexOutOfBoundsException("数组的索引越界");
}
int ele = arr[index];
return ele;
}
结果:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 数组的索引越界
at day05.DemoThrow.getElement(DemoThrow.java:20)
at day05.DemoThrow.main(DemoThrow.java:7)