异常处理的五个关键字:try,catch,finally,throw,throws。
1.抛出异常throw
作用:可以使用throw关键字在指定的方法中抛出指定的异常
使用格式:
throw new xxxException(“异常产生的原因”);
注意事项:
1.throw关键字必须写在方法的内部。
2.throw关键字后面new的对象必须是Exception或者Exception的子类对象。
3.throw关键字抛出指定的异常对象,我们就必须处理这个对象。
throw关键字后面是RuntimeException或者是它的子类对象时,我们可以不处理,默认交给JVM处理。
throw关键字后面是编译异常时(写代码的时候报错),我们就必须处理这个异常,要么throws(交给别人处理),要么try catch。
我写了一个代码,如下:
public class Test {
public static void main(String[] args) {
int arr[]=null;
int e=getElement(arr,0);
}
public static int getElement(int arr[],int index){
if (arr==null){
throw new NullPointerException("传递的数组的值是null");
}
int ele=arr[index];
return ele;
}
}
因为throw关键字后面接的是空指针异常,所以我们可以不去处理它,可以交给JVM去处理,我设置了一个if语句,如果传递的是一个空指针,那么就抛出空指针异常:传递的数组的值是null。
相应的,index也可以做一个检验,如果index的值超出了数组的索引范围,那我们就抛出异常:传递的索引超出了数组数组的索引范围,我也相应的写出了代码,如下:
public class Test {
public static void main(String[] args) {
int arr[]={1,2,3,4,5};
int e=getElement(arr,8);
}
public static int getElement(int arr[],int index){
if (arr==null){
throw new NullPointerException("传递的数组的值是null");
}
if (index<0||index> arr.length-1){
throw new ArrayIndexOutOfBoundsException("传递的索引超出了数组索引的范围");
}
int ele=arr[index];
return ele;
}
}
截止到现在,我们已经学习了两种throw的new了,NullPointerException(空指针异常)与ArrayIndexOutOfBoundsException(超出数组索引范围异常),都是RuntimeException的子类,是无需我们自己处理的。