异常处理的过程

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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值