繁体   English   中英

在java中的接口方法中抛出多个异常

[英]Throwing multiple exceptions in a method of an interface in java

我想问一下如何在我的界面中提及这一点

public class find(int x) throws A_Exception, B_Exception{
----
----
---
}

我想说我可以在界面中提到一个例外,但是如何在我的界面中提到我的方法会抛出两个例外,即A和B ......

上面提到的代码片段仅适用于A而不适用于B ...帮助

public interface dictionary{ 
   public void insert(int x) throws Dictionary_FullException, Duplicate_Element_FoundException; 
}
...
 public class SortedArray implements dictionary{ 
   public void insert(int x) throws Dictionary_FullException, Duplicate_Element_FoundException {
 ---------
}

但是当我编译它...它说..

在allocate.SortedArray中,SortedArray.java:66:insert(int)无法在assign.dictionary中实现insert(int); 重写方法不抛出assign.SortedArray.Duplicate_Element_FoundException public void insert(int x)throws Dictionary_FullException

您可以根据需要为接口方法声明任意数量的异常。 但是您在问题中提供的课程无效。 它应该读

public class MyClass implements MyInterface {
  public void find(int x) throws A_Exception, B_Exception{
    ----
    ----
    ---
  }
}

然后界面看起来像这样

public interface MyInterface {
  void find(int x) throws A_Exception, B_Exception;
}

我想你要求的代码如下:

public interface A
{
    void foo() 
        throws AException;
}

public class B
    implements A
{
    @Overrides 
    public void foo()
        throws AException,
               BException
    {
    }
}

除非BException是AException的子类,否则这将不起作用。 覆盖方法时,必须符合父提供的签名,并且例外是签名的一部分。

解决方案是声明接口也抛出BException。

原因是你不希望代码如下:

public class Main
{
    public static void main(final String[] argv)
    {
        A a;

        a = new B();

        try
        {
            a.foo();
        }
        catch(final AException ex)
        {
        }
        // compiler will not let you write a catch BException if the A interface
        // doesn't say that it is thrown.
    }
}

如果B :: foo抛出BException会发生什么? 该计划将不得不退出,因为它可能没有捕获。 为了避免这种情况,子类不能改变抛出的异常类型(除了它们可以从列表中删除异常)。

您需要在可以抛出异常的方法上指定它。 如果它可以抛出超过1种类型的异常,你只需用','分隔它们。 例如

public interface MyInterface {
  public MyObject find(int x) throws MyExceptionA,MyExceptionB;
}

暂无
暂无

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

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