无法覆盖父 class 的方法

Can't override a method of parent class

我在尝试重写父方法时遇到编译错误 class:

public class Reader {
    public void readToDbFromFile(String fileName, String table) throws FileNotFoundException() {
         ....
    }
}

public class ReaderWithBackup extends Reader {
    @Override
    public void readToDbFromFile(String fileName, String table) throws IOException {
        super.readToDbFromFile();
        doBackup(fileName, table);
    }

    ...
}

它说 'overriden method does not throw IOException'。这是什么意思?我该如何解决?

提前致谢。

重写方法抛出 FileNotFoundException,因此重写方法必须抛出 FileNotFoundExceptionFileNotFoundException 的子 class。 IOExceptionFileNotFoundException 的超 class,因此它不能被覆盖方法抛出。

考虑这段代码:

try {
    Reader reader = ...
    reader.readToDbFromFile(..);
}
catch (FileNotFoundException ex) {
    ..
}

这是有效代码,因为 ReaderreadToDbFromFile 方法只能抛出 FileNotFoundException 已检查异常。如果您覆盖 readToDbFromFileReader 的某个子 class,如果您将子 class 的实例分配给 reader,则此代码必须仍然有效] 多变的。因此,您的覆盖方法不能抛出原始方法的 throws 子句未涵盖的异常。

您不能在子 class 的重写方法中抛出超级 class 方法的 Parent Exception

由于 FileNotFoundExceptionIOException 的子 class,因此您不能将 IOException 扔给 class.

所以你可以通过交换 IOExceptionFileNotFoundException 来做到这一点:-

public class Reader {
    public void readToDbFromFile(String fileName, String table) throws IOException () {
         ....
    }
}

public class ReaderWithBackup extends Reader {
    @Override
    public void readToDbFromFile(String fileName, String table) throws FileNotFoundException{
        super.readToDbFromFile();
        doBackup(fileName, table);
    }

    ...
}

在你的父母 class readToDbFromFileFileNotFoundException。您应该在覆盖函数中抛出 FileNotFoundException 而不是 IOException