Exception与重写

子类重写基类中带Throws的方法,需要遵循以下规则:
1:不能扩大异常范围
也就是说子类方法必须为基类异常的类或子类

2:可不抛出异常

public class OverRideException extends OverRide{

    public void method1() {
        System.out.println("子类method1方法");
    }

    public void method2() throws FileNotFoundException{
        System.out.println("子类method2方法");
    }

    public static void main(String[] args) {
        OverRide over = new OverRideException();
        try {
            over.method1();
            over.method2();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class OverRide {
    public void method1() throws IOException {
        System.out.println("父类类method1方法");
    }

    public void method2() throws IOException{
        System.out.println("父类method2方法");
    }

}

输出:
子类method1方法
子类method2方法

解析:
子类method1中缩小了异常范围
子类method2中没有抛出异常

猜你喜欢

转载自blog.csdn.net/winer1220/article/details/49906753