子父类中的异常

2017-10-28  本文已影响0人  YOUNG_FAN

要点

Paste_Image.png

代码

class AException extends Exception {
    
    AException(String msg) {
        super(msg);
    }
}

class BException extends AException {
    
    BException(String msg) {
        super(msg);
    }
}

class Fu {
    
    private int state = 2; //状态值 1 :正常
     void method() throws AException {
        if (state == 2)
        throw new AException("A异常");
        System.out.println("fu method"); 
    }
}

class Text {
    
    void function(Fu f) {
        try{
            f.method();
        }
        catch(AException e) {
            System.out.println(e.toString());
        }
        System.out.println("OVER");
    }
}

class Zi extends Fu {
    
    private int state = 3; //状态值 1 :正常
     void method() throws BException { //或者抛 AException 
        if (state == 3)
        throw new BException("B异常");
        System.out.println("zi method"); 
    }
}

class ExceptionDemo7 {
    
    public static void main(String[] args) {
        
        Text t = new Text();
        t.function(new Zi());
    
    }
}

好好学java,天天哇哈哈
上一篇 下一篇

猜你喜欢

热点阅读