Cannot handle exception type thrown by implicit super constructor

末鹿安然 提交于 2019-12-06 04:14:45

问题


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 an object of Cage in another class main method:

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

I get the error: "Default constructor cannot handle exception type CageException thrown by implicit super constructor. Must define an explicit constructor." Any ideas? :o(


回答1:


This means that in the constructor of your other class you are creating the Cage class, but that constructor isn't properly handling the exception.

So either just catch the exception when you create the Cage class in the other constructor, or make the constructor throws CageException.




回答2:


You could use a use a helper method in the class where Cage gets instantiated:

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


来源:https://stackoverflow.com/questions/16952692/cannot-handle-exception-type-thrown-by-implicit-super-constructor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!