Java中的异常和继承 [英] Exception and Inheritance in Java

查看:209
本文介绍了Java中的异常和继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们遇到此问题

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

public class Child1 extends Father{
    public void method1() throws Exception{
    super.method1();
    ... 
    }

}

Child1 extends Father 并覆盖 method1 但是给出了实现 Child1.method1 现在抛出异常。这不会编译,因为重写方法不能抛出新的异常。

Child1 extends Father and overrides method1 but given the implementation Child1.method1 now throws a exception. This won't compile as the overriding method can't throw new exceptions.

什么是最佳解决方案?


  • 将所需的异常传播到。对我而言,这是针对封装,继承和一般OOP(可能会抛出永远不会发生的异常)。

  • 使用 RuntimeException 相反?此解决方案不会将 Exception 传播到,但Oracle文档和其他来源声明该类异常应该当客户端代码无法执行任何操作时使用。这不是那种情况,这个例外对于恢复blablabla很有用(为什么使用 RuntimeException 而不是?)。

  • 其他..

  • Propagate the required exception to the Father. To me this is against encapsulation, inheritance and general OOP (the Father potentially throws an exception that will never happen).
  • Use a RuntimeException instead? This solution won't propagate the Exception to the Father, but Oracle docs and other sources state that class of exceptions should be used when "Client code cannot do anything". This is not that case, this exception will be useful to recover blablabla (why is it wrong to use RuntimeException instead?).
  • Other..

推荐答案

使用RTE并不是一个坏主意。这是Spring框架的方法,它工作得很好。如果您正在实现应用程序可能使用此解决方案。

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.

如果您要实现公开API恕我直言的库,您应该使用已检查的异常。在这种情况下,您应该创建自己的异常,例如 BaseException 。方法方法() 将抛出它。 define ChildException扩展BaseException 并声明子类的 method1()以抛出它。

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.

这不破坏封装:基类抛出基本异常。它对具体的例外情况一无所知。 Child类抛出具体的异常但是扩展了基本异常,因此可以被客户端代码视为基本异常。

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.

作为一个例子,我可以给你 IOException FileNotFoundException 延伸它。您可以使用输入流捕获 IOException ,而具体流是 FileInputStream ,它会抛出 FileNotFoundException 。但客户不知道这一点。它捕获 IOException

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.

这篇关于Java中的异常和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆