程序不编译

时间:2013-11-23 04:06:56

标签: java

我正在阅读有关继承和异常的内容。当我尝试在控制台中编译以下代码时,我收到编译器错误。我仍然无法弄清楚原因。但是,如果我在B类中更改方法名称,一切正常。请帮忙。

这是我的代码:

import java.io.IOException;

class A {  

    public void print() throws IOException {
        System.out.println("In Class A.");
        throw new IOException("Printed in A.");
    }

}

class B extends A {

    public void print() throws Exception {
        System.out.println("In Class B.");
        throw new Exception("Printed in B.");
    }

}

public class TestPrint {

    public static void main (String args[]) {
        B b = new B();
        try {
            b.print();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

2 个答案:

答案 0 :(得分:4)

重写的方法不能抛出层次结构比原始方法更高的Checked Exception。

ExceptionIOException的超类。

因此,您的print()方法子类(B)可以抛出IOExceptionIOException的任何子类。

更改您的课程B,如下所示:

class B extends A {

    public void print() throws IOException {
        System.out.println("In Class B.");
        throw new IOException("Printed in B.");
    }

}

答案 1 :(得分:1)

在重写方法中,不能在继承层次结构中抛出更高的异常,即IOException是异常类的子类。

您可以在重写方法

中抛出任何IOException的子类异常