异常处理

异常处理:
首先看一段出现异常的代码:

public class ExcDemo {
    public static void main(String[] args) {
        int[] arr = new int[3];
        System.out.println("------begin-----");
        System.out.println(arr[4]);
        System.out.println("------over------");
    }
}

在这里插入图片描述
异常的处理方法:
方式一:将异常捕获:try-catch

try{
可能出现异常的语句
}catch(异常的类型 对象){
异常的处理方式
}finally{
出口—(finally块一定会被执行)
}
在上面的代码中,catch块可以出现多次,组合方式有以下几种

  • try…catch
  • try…finally
  • try…catch…finally

异常处理:

 public static void main(String[] args) {
        int[] arr = new int[3];
        System.out.println("------begin-----");
        try{
            System.out.println(arr[4]);
        }catch (ArrayIndexOutOfBoundsException e){
            System.out.println("异常处理");
        }
        System.out.println("------over------");
    }

在这里插入图片描述
可以看到将异常捕获后,程序不会卡在出现异常的地方,会在异常处理后继续执行后面的代码
在catch块中可以调用异常类中的printStackTrace()方法打印错误堆栈信息
在这里插入图片描述
方式二: 将异常抛出
throw关键字: 用在方法内部,表示可以人为将异常抛出

public static void main(String[] args) {
        int[] arr = new int[4];
        System.out.println("------begin-----");

        if (arr.length == 3){
            System.out.println("是指定大小的数组");
        }else {
            throw new ArrayIndexOutOfBoundsException("数组长度错误");
        }

        System.out.println("------over------");
    }

在这里插入图片描述
throws关键字: 用在方法声明处,表示调用此方法会产生异常,但是我并没有将异常处理,抛到上层进行处理

public class ExcDemo {
    public static void main(String[] args) {
        int[] arr = new int[1];
        System.out.println(getvalue(arr));
    }
    public static int getvalue(int[] arr)throws ArrayIndexOutOfBoundsException{
        if (arr.length == 0){
            throw new NullPointerException("空数组");
        }
        return arr[3];
    }
}

在这里插入图片描述

多catch块处理:
当抛出的多个异常之间有继承关系时,必须先捕获子类的异常,因为子类的异常类对象可通过天然的向上转型自动被父类所接受
总结

  • 运行时异常发生时,不建议使用异常捕获的方式进行异常处理,比如数组中的空指针异常,发生异常后后面的代码没有运行的必要,应该停止程序,修改代码
  • 方法重写时,若父类的方法抛出异常。子类重写后的方法可以抛也可以不抛
  • 父类方法不抛异常。子类重写后的方法不能抛异常
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值