【问题标题】:Is parent child hierarchy important on throws while overriding.?覆盖时,父子层次结构对抛出很重要。?
【发布时间】:2017-03-20 01:13:53
【问题描述】:

请在下面找到我的代码,我想澄清我关于覆盖和抛出异常的概念。下面提供的代码会起作用吗,如果是,那为什么。?我问这个问题是因为 IOException 和 ArithmeticException 之间没有直接的父子关系。

public class TestExceptionChild {

    public static void main(String[] args) {
        Parent parent = new Child();
        try {
            parent.msg();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

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

class Child extends Parent{  
    void msg() throws ArithmeticException{
        System.out.println("child");
    }  
}

【问题讨论】:

    标签: java oop exception polymorphism overriding


    【解决方案1】:

    这会起作用,但只是因为ArithmeticException 扩展了RuntimeException(即它不是一个检查异常,所以这里不需要使用throws 子句)。如果您使用检查异常而不是ArithmeticException,则它必须是或扩展类型IOException。否则会出现编译错误。

    所以要回答您的问题,是的,层次结构对于已检查 异常很重要。详情请见here

    【讨论】:

    • IOException 不是 RuntimeException。为什么覆盖方法不需要也有throws IOException?怎么会抛出nothing,却不会抛出另一种被检查的异常?
    • @Gendarme 您可以将“无所事事”视为throws IOException 的子集。然而,反之亦然。如果父级什么都不抛出,则被覆盖的子级不能抛出已检查异常。
    • 我会将其添加到答案中。
    • 那么这是否意味着层次结构对于父方法抛出已检查异常而子方法抛出未检查异常的情况无关紧要......?
    • @RajBhatia throws 用于检查异常。排除文档目的,对于未经检查的异常没有意义。
    猜你喜欢
    • 1970-01-01
    • 2011-04-23
    • 1970-01-01
    • 2020-05-29
    • 1970-01-01
    • 1970-01-01
    • 2012-03-11
    • 2021-07-04
    • 2021-01-08
    相关资源
    最近更新 更多