2013-06-06 41 views
4

拋出我有一個籠類:無法處理的異常類型隱式超級構造

public class Cage<T extends Animal> { 

    Cage(int capacity) throws CageException { 
     if (capacity > 0) { 
      this.capacity = capacity; 
      this.arrayOfAnimals = (T[]) new Animal[capacity];              
     } 

     else { 
      throw new CageException("Cage capacity must be integer greater than zero"); 
     } 
    } 
} 

我試圖實例凱奇的對象在另一個類的主要方法:

private Cage<Animal> animalCage = new Cage<Animal>(4); 

我得到的錯誤:「默認構造函數不能處理由隱式超級構造函數拋出的異常類型CageException,必須定義一個顯式構造函數。」有任何想法嗎? :O(

回答

5

這意味着,在你的其他類的構造函數,你所創建的凱奇類,但構造函數沒有正確處理異常

所以,要麼只是捕獲異常當您創建Cage。在其他類的構造函數,或使構造函數拋出CageException

+0

真的很了不起的Th謝謝你!我只用一種主要方法在課堂上做這件事;我通常不會爲此創建構造函數。再次感謝。 – LanneR

2

你可以使用一個使用在類的幫助方法,其中Cage被實例化:。

class CageInstantiator { 
    private Cage<Animal> animalCage = getCage(); 

    private static Cage<Animal> getCage() { 
     try { 
      return new Cage<Animal>(4); 
     } catch (CageException e) { 
      // return null; // option 
      throw new AssertionError("Cage cannot be created"); 
     } 
    } 
} 
+0

謝謝,Reimeus! – LanneR

相關問題