java138-异常处理

//异常
public class test79 {
    //定义方法声明定义异常,在满足条件时抛出异常对象,程序转向异常处理
    public double count(double n,double m)throws Exception {
        if (m == 0) {//如果除数等于0.则抛出异常实例
            throw  new Exception("对不起。除数不能等于0");
        }
        return n/m;
    }
}
测试类

public class test81 {
    //定义了编译异常的方法调用,必须进行显示处理
    public static void main(String[] args){
        test79 com=new test79();
        try {
            double t=com.count( 78,0 );
            System.out.println( t );
        }catch (Exception e){
            String msg=e.getMessage();
            System.err.println(msg);
            e.printStackTrace();//打印异常轨迹
        }
    }
}
运行结果

 

posted @ 2022-06-25 15:26  前端导师歌谣  阅读(38)  评论(0)    收藏  举报