throw关键字
**作用:**可以使用throw关键字在指定的方法中抛出指定的异常
使用格式:
throw new xxxException(“原因”)
注意:
1、throw关键字必须写在方法的内部
2、后边new的对象必须是Exception或者Exception的子类对象
3、throw关键字抛出指定的异常对象,必须处理这个异常对象
throw关键字后边创建的是runtimeException或者是runtimeException的子类对象,可以不处理默认交给JVM处理
创建的是编译异常,必须处理这个异常 throw或者try catch
public class demo03Throw {
public static void main(String[] args) {
int[]arr= new int[3];
int e = getElement(arr, 5);
System.out.println(e);
}
/*
定义一个方法 获取数组指定索引处的元素
参数: int[] arr
int index
工作中:必须首先对方法传递过来的参数进行合法性校验 如果参数不合法,则必须抛出异常。
NullPointerException是一个运行期异常,不用处理,默认交给JVm处理
*/
public static int getElement(int[] arr,int index){
/*
进行合法性校验
如果数组arr的值是null 则抛出异常
*/
if(arr == null){
throw new NullPointerException("空指针异常");
}
/*
可以对传递过来的参数index进行合法性校验
如果index的范围不在数组的索引范围内
则抛出数组越界异常
*/
if(index<0 ||index> arr.length-1){
throw new ArrayIndexOutOfBoundsException("索引越界");
}
int ele = arr[index];
return ele;
}
}