throw 关键词
作用:可以使用throw关键字在指定的方法中抛出指定的异常
使用格式:throw new XXXException(“异常产生的原因”);
注意:1、throw 关键字必须写在方法内部
2、throw关键字后面new的对象必须是Exception或者时Exception的子类对象
3、throw关键字抛出指定的异常对象我们就必须处理这个对象
throw关键字后面创键的是RuntiamException或者是RuntaimException的子类对象,我们可以不用处理,默认交给JVM处理
(打印异常对象,中断程序)
throw关键字后面创建的是编译异常(写代码时报错,我们就必须处理这个异常,要么throw,要么try…catch)
public class demoException {
public static void main(String[] args) {
int [] arr=null;
int a=getElement(arr,0);
System.out.println(a);
}
/*定义一个方法,获取数组指定索引的元素
参数;interesting【】 arr ,int index
以后工作中我们必须对方法传递过来的参数进行合法校验
如果参数不合法,那么我们就必须使用抛出的异常方方式告知方法的调用者,传递的参数有问题*/
public static int getElement(int[] arr,int index){
if (arr==null){
throw new NullPointerException("传递的数组的值是null");
}
int ele=arr[index];
return ele;
}
}
Objects类中的静态方法判断非空
Objects类中的静态方法判断非