1.JVM虚拟机默认处理异常方式 2.try catch 捕获异常 3.捕获异常灵魂四问

 

 

 

public class demo {
    public static void main(String[] args) {

        int arr[]={1,2,3,4};
        try {
            //可能会报错的代码
            System.out.println(arr[10]);
         //catch(括号里面写 上面报错的原因  一致就被捕获然后继续运行下面的代码)
        }catch (ArrayIndexOutOfBoundsException e){
            System.out.println("索引越界");
        }
        System.out.println("看看执行了嘛");
    }
}

 

 

public class demo {
    public static void main(String[] args) {
        int arr[]={1,2,3,4};
        try {
            //try中没有错的代码
            System.out.println(arr[0]);
        }catch (ArrayIndexOutOfBoundsException e){
            System.out.println("索引越界");
        }
        System.out.println("看看执行了嘛");
    }
}

 灵魂一问   会把try中代码全部执行一遍 跳过catch 也就是不会执行catch里面的代码

public class demo {
    public static void main(String[] args) {
        int arr[]={1,2,3,4};
        try {
            //俩个错误  得写俩个catch  父类Exception 必须写在最下面  要不然就会其他catch报错
            System.out.println(arr[10]);
            System.out.println(2/0);
        }catch (ArrayIndexOutOfBoundsException e){
            System.out.println("索引越界");
        }catch (ArithmeticException e){
            System.out.println("算数异常");
        }catch (Exception e){
            System.out.println("Exception");
        }
        System.out.println("看看执行了嘛");
    }
}

  灵魂二问  要写多个catch与之对应    细节要是catch有父子关系  那么父类一定写最下面

了解 jdk7以后 catch可以捕获多个异常 中间用  |   隔开

 

灵魂三问  try catch白写  异常直接交给虚拟机处理   就直接运行报错那种

灵魂四问  下面代码不会运行  直接跳转catch 里面的代码执行    如果没有catch与之匹配  异常直接交给虚拟机处理   就直接运行报错那种 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值