El proceso de manejo de excepciones

package Day19;/*
 *@author wanghongyuan
 *@Create 2020/12/28 7:25
 */
/*
    下面这个异常出现系统会做三件事情:
    1.是在主方法执行的时候,跳到了getElement方法里面,发现这个方法访问数组的索引“3”,而数组中并没有“3”这个索引
      这个时候,JVM就会输出程序异常
      JVM做了两件事:
      (getElement方法把异常对象抛给main方法)
      1.JVM会根据异常产生的原因创建一个异常对象,这个异常对象包含了异常产生的(内容,原因,位置)
ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
      2.getElement方法中没有处理异常的处理逻辑(try....catch),那么JVM就会把这个异常对象抛出给方法的调用者
         main方法来处理这个异常。
   (main方法把异常对象抛出给JVM)
    2.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
        main方法接收到了这个异常对象,main方法也没有这个异常处理的逻辑
        继续把这个异常抛出给main方法的调用者JVM处理。
   3.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
         JVM接收到了这个异常对象,做了两件事情
            1.把异常对象的(内容,原因,位置)以红色的字体打印在控制台
            2.Jvm会终止当前还在运行的java程序-->中断处理

 */
public class Demo02Exception {
    
    
    public static void main(String[] args) {
    
    
        int[] arr = {
    
    1,2,3};
        int e = getElement(arr, 3);
        System.out.println(e);
    }

    private static int getElement(int[] arr, int i) {
    
    
        int ele = arr[i];
        return ele;
    }
}

package Day17;/*
 @Author wanghongyuan
  @Date 2020/12/28 
 
*/

public class Demo01Throw {
    
    
    public static void main(String[] args) {
    
    
        // int[] arr ={3,4};
        // int[] arr = null;
        int[] arr = new int[3];
        int w = getElement(arr, 2);
        System.out.println(w);
    }

    private static int getElement(int[] arr,int index) {
    
    
        if (arr == null){
    
    
            throw new NullPointerException("空指针异常");
        }else if (index<0 || index> arr.length-1){
    
    
            throw new IndexOutOfBoundsException("数组索引越界异常");
        }
        int arr1 = arr[index];
        return arr1;
    }
}

Supongo que te gusta

Origin blog.csdn.net/weixin_41977380/article/details/111829777
Recomendado
Clasificación