java 无法处理隐式超级构造函数抛出的异常类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16952692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:30:04  来源:igfitidea点击:

Cannot handle exception type thrown by implicit super constructor

javaoopsubclass

提问by

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:

我正在尝试在另一个类 main 方法中实例化 Cage 的对象:

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(

我收到错误消息:“默认构造函数无法处理隐式超级构造函数抛出的异常类型 CageException。必须定义一个显式构造函数。” 有任何想法吗?:o(

采纳答案by greedybuddha

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.

这意味着在其他类的构造函数中,您正在创建 Cage 类,但该构造函数没有正确处理异常。

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

因此,要么Cage在其他构造函数中创建类时捕获异常,要么使构造函数 throws CageException

回答by Reimeus

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

您可以在Cage实例化的类中使用 use a helper 方法:

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