Java -- 异常的捕获及处理 -- 范例 -- throw与throws的应用

  7.2.3 范例 -- throw与throws的应用

    例:综合应用

    Class : Math

package limeThrowable._7_2_3;

public class Math {

    public int div(int i, int j) throws Exception {        //方法可以不处理异常
        System.out.println("******计算开始******");
        int temp = 0;        //声明整型变量
        try {
            temp = i / j;        //如果产生异常,则执行catch
        } catch (Exception e) {        //捕获异常
            throw e;        //把异常交给被调用处
        } finally {        //不管是否产生异常都执行此代码
            System.out.println("******计算结束******");
        }
        return temp;

    }
}

    Class : main

package limeThrowable._7_2_3;

public class ThrowDemo02 {

    public static void main(String[] args) {
        Math m = new Math();
        
        try {
            System.err.println("除法操作:" + m.div(10, 0));
        } catch (Exception e) {
            System.out.println("异常产生:" + e);
        }
    }
}

    Console : 

******计算开始******
******计算结束******
异常产生:java.lang.ArithmeticException: / by zero

7.3 Exception 类 与 RuntimeException类

啦啦啦

原文地址:https://www.cnblogs.com/ClassNotFoundException/p/7010404.html