Exception and Inheritance in Java

后端 未结 5 1945
旧巷少年郎
旧巷少年郎 2021-01-04 12:59

Suppose we have this problem

public class Father{
    public void method1(){...}
}

public class Child1 extends Father{
    public void method1() throws Exce         


        
5条回答
  •  说谎
    说谎 (楼主)
    2021-01-04 13:37

    Using RTE is not a bad idea. This is the methodology of Spring framework and it works quite fine. If you are implementing application probably use this solution.

    If however you are implementing library that exposes API IMHO you should use checked exception. In this case you should create your own exception for example BaseException. Method method() of Father will throw it. The define ChildException extends BaseException and declare method1() of child class to throw it.

    This does not break encapsulation: base class throws base exception. It does not have any idea about the concrete exception. Child class throws concrete exception that however extends base exception and therefore can be treated by client code as base exception.

    As an example I can give you IOException and FileNotFoundException that extends it. You can work with input stream catching IOException while the concrete stream is FileInputStream and it throws FileNotFoundException. But client does not know this. It catches IOException.

提交回复
热议问题