简体   繁体   English

Java:如何重写方法并引发异常?

[英]Java : How to override a method and throw exception?

I'm trying to override a method, with throwing an exception: 我试图通过抛出异常来覆盖方法:

class A {

    public doSomething(){
        // some of logic
    }

}


class B extends A {

    public doSomething() throws MyCustomizedException {
        try {
             // some of logic
        } catch(ExceptionX ex ) {
             throw new MyCustomizedException(" Some info ", ex);
        }
    }      
}

But I get this compile time error : 但是我得到这个编译时错误:

Exception MyCustomizedException is not compatible with throws clause in A

The two constraints are : 这两个约束是:

  • Using the same name of the function and the same arguments if they exist: doSomething() 使用相同的函数名称和相同的参数(如果存在): doSomething()
  • Throwing my customized exception 抛出我的自定义异常

How can I get rid of the exception? 如何摆脱异常?

Thank you a lot. 非常感谢。

Cannot be done. 无法完成。

When you override a method, you can't break the original contract and decide to throw a checked exception. 当您覆盖方法时,您将无法打破原始合同并决定引发已检查的异常。

You can make MyCustomizedException unchecked. 您可以取消选中MyCustomizedException You can throw it, but you can't require that users handle it the way you can with a checked exception. 您可以抛出它,但不能要求用户以受检查的异常来处理它。 The best you can do is add it to the javadocs and explain. 最好的办法是将其添加到javadocs中并进行解释。

This is not a overloading case. 这不是一个超载的情况。 To overload you need methods with same signature but different argument list. 要重载,您需要具有相同签名但参数列表不同的方法。 This is Overriding, Use public doSomething() throws MyCustomizedException {} in class A if Class A can modify. 这是重写,如果Class A可以修改,则使用public doSomething() throws MyCustomizedException {}在Class A中public doSomething() throws MyCustomizedException {}

Now you can override with your current implementation for class B. 现在,您可以使用当前的B类实现重写。

The only way you can do this is to make the exception that you are throwing extend RuntimeException instead of Exception. 您执行此操作的唯一方法是使您抛出的异常扩展为RuntimeException而不是Exception。

This way you will be able to throw it as you don't change the compact of the method, unfortunately the compiler will not automatically detect that you need to catch that exception but depending on how you are using it that may not be a problem. 这样,您就可以在不更改方法的紧凑性的情况下抛出它,不幸的是,编译器不会自动检测到您需要捕获该异常,而是取决于您如何使用它,这可能不是问题。

There is actually a way to do this - using composition rather than inheritance: 实际上,有一种方法可以做到这一点-使用组合而不是继承:

class B {
   A a = new A();
   void doSomething() throws MyException {
      a.doSomething();
      throw MyException();
   }
}

Of course by doing this your B no longer counts as an A so cannot be passed to anything expecting an A. You could use a B throughout your code though and just wrap As on demand. 当然,通过这样做,您的B不再计为A,因此不能传递给任何期望A的对象。尽管如此,您可以在整个代码中使用B,并仅按需包装As。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM