Cannot handle exception type thrown by implicit super constructor

I have a Cage class:

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"); } } } 

I am trying to instantiate a Cage object in the main method of another class:

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

I get an error: "The default constructor cannot handle the type of CageException thrown by the implicit superconstructor. Must define an explicit constructor." Any ideas ?: About (

+4
source share
2 answers

This means that in the constructor of your other class, you are creating the Cage class, but this constructor does not properly handle the exception.

So either just catch the exception when creating the Cage class in another constructor, or throw a CageException .

+5
source

You can use the helper method in the class where Cage gets the instance:

 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"); } } } 
+2
source

Source: https://habr.com/ru/post/1484753/


All Articles