异常

public class Note6 {
    public static void main(String[] args) {
        int a =4;
        int b=0;
        int result=a/b;
        System.out.println("xxxx");
    }
}
程序的异常

程序异常的现实世界参照物:生病

异常体系:
Throwable
    ----------Error
              该分支下的异常,就像生活中,无法处理的疾病一样,发生了该异常,你程序员没能力处理它
    ----------Exception
              该分支下的异常,就像现实生活中,感冒,骨折等可以处理的疾病一样发生了该类异常程序员可以去处理的

那该怎么解决呢?

try{
    可能会出现异常的代码
}catch(异常类型 变量名){
    处理异常的代码
}
public class Note6 {
    public static void main(String[] args) {
        int a = 4;
        int b = 0;
        try {
            int result = a / b;

        } catch (ArithmeticException ex) {
            //只需要出现ArithmeticException类型的异常,本代码就会被执行
            System.out.println("出异常了!除数不能为0");
        }
        System.out.println("xxxx");
    }
}

 异常被捕获到的话程序就不会挂掉

public class Note6 {
    public static void main(String[] args) {
        int a = 4;
        int b = 6;
        int[] arr=new int[5];
        try {
            int result = a / b;
            //数组下标越界异常
            arr[5]=10;
            //如果上面代码出现异常的话异常后面的代码就不会被执行
            System.out.println("出现异常不执行");
        } catch (ArithmeticException ex) {//Exception ex = new ArithmeticException;
            //这样写不好因为不能具体问题具体分析了,只要出现异常都会被Exception识别
            //只需要出现ArithmeticException类型的异常,本代码就会被执行
            System.out.println("出异常了!除数不能为0");
        }
        catch (ArrayIndexOutOfBoundsException ex) {//Exception ex = new ArithmeticException;
            //这样写不好因为不能具体问题具体分析了,只要出现异常都会被Exception识别
            //只需要出现ArithmeticException类型的异常,本代码就会被执行
            System.out.println("出异常了!数组下标越界了!");
        }
        System.out.println("程序结束");
    }
}

异常是可以写多个的

在try代码中如果出现异常被捕获到,那么异常代码后面的代码不会被执行

因为最上面的异常是绝大部分异常的父类会捕获很多异常所以后面的catch代码永远都不会被执行所以java不允许这样的情况

这样写的话就不会报错了

 

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值