Day6 异常

这篇博客介绍了Java中常见的异常类型,包括Exception和Error,以及如何创建自定义异常类。示例展示了如何通过继承Exception类来定义一个名为Chap1的自定义异常,并在方法中抛出和捕获。此外,还讲解了使用try-with-resources结构进行异常捕获和资源管理的方式。
摘要由CSDN通过智能技术生成

Day6 异常

常见异常

请添加图片描述

  • Exception: 用于用户程序可能出现的异常情况,它也是用来创建自定义异常类型类的类。
  • Error:定义了在通常环境下不希望被程序捕获的异常。一般指的是 JVM 错误,如堆栈溢出。

自定义异常

// 自定义异常Chap1:继承Exception
public class Chap1 extends Exception{
    // 自定义异常类中的信息
    private Integer code;
    // message这个属性来自父类,可以直接使用,不用定义
    public Chap1(String message, Integer code) {
        super(message);
        this.code = code;
    }
    @Override    // 重写输出格式
    public String toString() {
        return "Chap1{" +
                "message=" + super.getMessage() +
                "code=" + code +
                '}';
    }
}

class Test1{
    // throws Chap1:  将该异常交给下一级去处理
    public static int add(int a, int b) throws Chap1 {
        int result = a + b;
        if (result < 1){
            // 使用自定义的异常抛出,会结束该方法
            throw new Chap1("自定义异常", 400);
        }
        return result;
    }

    public static void main(String[] args) {
        // 前面抛出了异常,这里需要捕获处理
        try {
            add(-2, 0);
        }catch (Chap1 chap1){
            chap1.printStackTrace();
        }finally {
            System.out.println("不管怎样都会执行的语句");
        }
    }
}

异常捕获(try-with-resources

  • 面对必须要关闭的资源,可以多使用
  • 任何 catchfinally 块在声明的资源关闭后再运行
try (BufferedInputStream bin = new BufferedInputStream(new FileInputStream(new File("test.txt")));
     BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(new File("out.txt")))) {
    int b;
    while ((b = bin.read()) != -1) {
        bout.write(b);
    }
}
catch (IOException e) {
    e.printStackTrace();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值