Day08 JAVA学习笔记之异常

本文介绍了Java中的异常处理机制,包括try-catch-finally块的使用,如何捕获和处理多个异常,以及如何在方法中主动抛出异常。同时,通过实例展示了如何自定义异常类并进行异常的抛出和捕获。强调了finally块在资源管理中的重要性,以及在预见异常情况下如何优雅地控制程序流程。
摘要由CSDN通过智能技术生成

什么是异常

 

 

 异常处理机制

 

 

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

        try {//try监控区域
            System.out.println(a/b);
        }catch (ArithmeticException e){//catch(想要捕获的异常类型) 捕获异常
            System.out.println("程序出现异常,变量b不能为0");
        }finally {//处理善后工作 无论是否有异常都会执行这一步
            System.out.println("finally");
        }

        //finally 可以不要
        //如果涉及IO流和资源相关的东西,需要关闭,则需要finally
    }

}

如果没有try{}这输出红色的异常信息

 

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

        //假设要捕获多个异常,要从小到大排列

        try {//try监控区域
            System.out.println(a/b);
        }catch (Error e){//catch(想要捕获的异常类型) 捕获异常
            System.out.println("Error");
        }catch (Exception e){
            System.out.println("Exception");
        }catch (Throwable e){
            System.out.println("Throwable");
        }finally {//处理善后工作 无论是否有异常都会执行这一步
            System.out.println("finally");
        }

        //finally 可以不要
        //如果涉及IO流和资源相关的东西,需要关闭,则需要finally
    }

}

 

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

        try {
            new Test().test(1,0);
        } catch (ArithmeticException e) {
            e.printStackTrace();
        }

    }

    public void test(int a,int b)throws ArithmeticException{
            if(b==0){// throw throws
                throw new ArithmeticException();//主动的抛出异常,一般在方法中使用
            }

        System.out.println(a/b);
    }

}

 如果异常在意料之中,及在try{}内,程序遇到对应异常时就会抛出异常,并继续执行程序。

自定义异常 

 

//自定义的异常类
public class MyException extends Exception{
     //传递数字>10;
    private int detail;

    public MyException(int a){
        this.detail = a;
    }

    //toString:异常的打印信息

    @Override
    public String toString() {
        return "MyException{" +
                "detail=" + detail +
                '}';
    }
}
public class Test {
    //可能会存在异常的方法

    static void test(int a) throws MyException{

        System.out.println("传递的参数为:"+a);

        if(a>10){
            throw new MyException(a);//抛出
        }

        System.out.println("OK");
    }

    public static void main(String[] args) {
        try {
            test(11);
        } catch (MyException e) {
            System.out.println("MyException=>"+e);
        }
    }
}

总结

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值