簡體   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