Day16-02 P77 异常01:Error和Exception P78 异常02:捕获和抛出异常 P79异常03:自定义异常及经验小结 P80 JavaSE总结

这篇博客介绍了Java中的异常处理机制,包括Error、Exception的区分,以及如何捕获和抛出异常。通过示例代码展示了多层次的catch块用于捕获不同类型的异常,并探讨了finally块在资源管理中的作用。此外,还讨论了如何自定义异常以及在方法间传递异常。最后,文章总结了异常处理的经验和注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Day16-02

P77 异常01:Error和Exception

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述



P78 异常02:捕获和抛出异常

在这里插入图片描述

package com.exception;

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

        int a = 1;
        int b = 0;

        //假设要捕获多个异常:我们需要从小到大的catch捕获

        try { //try监控区域
            System.out.println((a/b));
        }catch (Error e){ //catch(想要捕获的异常类型) 捕获异常
            System.out.println("Error");
        }catch (Exception e) {
            System.out.println("Exception");
        }catch (Throwable t) {
            System.out.println("Throwable");
        }
        finally {  //处理善后工作
            System.out.println("finally");
        }
        //try catch 必须有,finally可以不要,  假设IO, 资源, 关闭!

        // System.out.println((a/b));//运行这个会出错,用上边那个
                   //try catch finally 处理异常

    }

    public void a(){
        b();
    }
    public void b(){
        a();
    }



}

package com.exception;

public class Test2 {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;

        //System.out.println((a/b));//选中这一行按住CTRL+alt+t快速生成try
                                  // 生成try catch finally 如下:
        try {
            System.out.println((a/b));
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
        }

        try{
            if (b==0){ //主动的抛出异常 throw throws
                throw new ArithmeticException();//主动的抛出异常
            }
        }
    }
}

package com.exception;

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

        try {
            new Tqwe().test(1,2);
        } catch (ArithmeticException e) {
            throw new RuntimeException(e);
        }

    }

    //假设这方法中,处理不了这个异常。方法上抛出异常
    public void test(int a,int b) throws ArithmeticException{
        if (b==0){ //throw throws
            throw new ArithmeticException();//主动的抛出异常,一般在方法中使用
        }
        System.out.println(a/b);
    }
}



P79 异常03:自定义异常及经验小结

在这里插入图片描述

在这里插入图片描述



P80 JavaSE总结

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值