首页 > 解决方案 > 异常处理中的方法覆盖

问题描述

在异常处理中,众所周知,如果超类方法不声明异常,子类重写方法不能声明已检查异常,但可以声明未检查异常。为什么这样?考虑以下示例:

import java.io.*;

class Parent {
    void msg() {
        System.out.println("parent");
    }
}

class TestExceptionChild extends Parent {
    void msg() throws IOException {
        System.out.println("TestExceptionChild");
    }

    public static void main(String args[]) {
        Parent p = new TestExceptionChild();
        p.msg();
    }
}

我试过的:

我们在这里得到编译错误。如果我需要在重写方法“msg”中读取文件,那么我必须在此处提及“throws IOException”。但是java不允许它们。谁能解释一下?

标签: exception-handlingtry-catch-finally

解决方案


您需要记住一件事,如果您使用 throws 关键字,那么出现的任何异常都将被转发到调用链中,并且如果在编译时重写,编译器会检查天气,重写的方法是否存在于父类中,并且 JVM 执行子类方法. 因此,基本上从父方法调用子方法,因此如果子方法抛出任何异常,否则它应该能够处理检查的异常,否则 CE .. 我希望它有帮助:)


推荐阅读