throw关键字 作用:可以使用throw关键字在指定的方法中抛出指定的异常 使用格式: throw new xxxException(“异常产生的原因”) 注意: 1.throw关键字必须写在方法的内部 2.throw关键字后面new的对象必须是Exception或者Exception的子类对象(ArrayIndexOutOfBoundsException NullPointerException等Exception的子类对象) 3.throw关键字抛出指定的异常对象,我们就必须处理这个异常对象 throw关键字后边创建的是RuntimeException(运行期异常)或者是RuntimeException的子类对象,我们可以不处理,交给JVN处理(打印异常对象,中断程序) throw关键字后边创建的是编译异常(写代码的时候报错是编译异常),就必须处理要么throws抛出要么try...catch
package Demo01;
public class text02 {
public static void main(String[] args) {
//创建数组
int[] arr ={1,2};
int e = getElement(arr,3); //注意这里是3
System.out.println(e);
}
public static int getElement(int[] arr , int index ){
if(arr==null){
throw new NullPointerException("传递的数组的值是null");
}
if(index<0||arr.length
注意几点:首先运行期异常会抛出异常对象 而且不用处理 jvm自己就处理了
其次是其实出了这种异常就是控制台会把throw的呢句话给抛出来 与不写throw的区别就是这样会很明显 看下面
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 2 没写throw
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 传递的索引超出了数组的使用范围 洗了throw



