07 Java异常机制(二)——异常处理机制

二、Java异常处理机制

异常处理的五个关键字:try、catch、finally、throw、throws

1.捕获异常

Ctrl+Alt+T 快捷键,选中语句后,自动生成if\else\try\catch等代码块包裹

package com.exception;

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


        try {//try监控局域
            System.out.println(a / b);
        } catch (ArithmeticException e) {//捕获异常
            System.out.println("程序出现异常,变量b不能为0");
        } finally {//处理善后工作,可选不要
            System.out.println("finally");
        }

        //可以不要,但是IO资源时,需要用来关闭
    }

}

package com.exception;

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

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

        try {//try监控局域
            System.out.println(a / b);
        } catch (ArithmeticException e) {//捕获异常
            System.out.println("程序出现ArithmeticException异常");
        } catch (Error e) {//
            System.out.println("程序出现Error异常");
        } catch (Exception e) {//
            System.out.println("程序出现Exception异常");
        } catch (Throwable e) {//等级最高的就是Throwable,最大的要写在最后面
            System.out.println("程序出现Throwable异常");
        } finally {//处理善后工作,可选不要
            System.out.println("finally");
        }

        //可以不要,但是IO资源时,需要用来关闭


    }

    public void a() {
        b();
    }

    public void b() {
        a();
    }


}

2.抛出异常

package com.exception;

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

        try {
            new Demo01().test(a, b);
        } catch (ArithmeticException e) {
            e.printStackTrace();
        }

    }

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

throw 和 throws 的区别
1)throw:

  • 表示方法内抛出某种异常对象。
  • 如果异常对象是非 RuntimeException 则需要在方法申明时加上该异常的抛出 即需要加上 throws 语句 或者 在方法体内 try catch 处理该异常,否则编译报错执行到 throw 语句则后面的语句块不再执行

2)throws:

  • 方法的定义上使用 throws 表示这个方法可能抛出某种异常,
  • 需要由方法的调用者进行异常处理
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值