异常捕获

package math;

public class YiChangBuHuo {
    private int a;
    private int b;
    
    public YiChangBuHuo(int a, int b) {
        this.a = a;
        this.b = b;
    }
    public int sub() throws SubException{
        if (a<b){
            throw new SubException();//抛出异常不做处理,继续抛出
        }
        return a-b;
    }
    
}
//自定义的异常(减数大于被减数的异常)
class SubException extends Exception{
    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Override
    public String getMessage() {
        // TODO Auto-generated method stub
        return "减数大于被减数!";
    }
}
//============================

package math;

public class Test1 {
    public static void main(String[] args) {
        YiChangBuHuo E=new YiChangBuHuo(8, 10);
        try {
            int cha=E.sub();//谁调用sub()方法,谁处理异常
            System.out.println("差为"+cha);
        } catch (SubException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
            System.out.println(e.getMessage());
        }
    }

}

posted on 2018-02-27 16:37  空对月  阅读(148)  评论(0编辑  收藏  举报