在构造函数中捕获异常

Alv*_*pik 5 java

public class AnimalException extends Exception {
    public AnimalException(String error) {
        super(error);
    }
}

public class Zoo {
    private String animal;
    private String food;

    public Zoo (String animal, String food) throws AnimalException {
        this.animal = animal;
        if (findWord(animal, "wolf")) {
            throw new AnimalException("This animal is a predator.");
            //something ought to be done here, I reckon
        }
        else {
            this.food = food;
        }


    }

    public static boolean findWord(String word, String find) {
        int total = 0;
        int idx = 0;
        while ( (idx = word.indexOf(find, idx))!= -1 ) {
            total++;
            idx++;
        }
        if (total == 0) {
            return false;
        }
        else {
            return true;
        }
}
Run Code Online (Sandbox Code Playgroud)

我想要做的是当wolf在构造函数中捕获a时,值food会自动更改为其他内容.我确实尝试过getter-setters,但是,我得到了错误unreachable code.我该怎么办?

Zer*_*ges 1

您的设计问题是,调用throw exception离开了块的范围,并正在寻找try-catch可以处理异常的块。在你的情况下

void foo() {
    if (somethingbad()) {
        throw new exception();
        bar(); // <-- unreachable code, since throw leaves foo function.
    }
}
Run Code Online (Sandbox Code Playgroud)

如果在构造函数中抛出异常并且异常离开函数,因为try-catch构造函数中没有该异常,则该对象的构造将失败。因此,如果您Zoo禁止将狼作为动物,您应该抛出异常(因此Zoo永远不会被创建)。

public Zoo (String animal, String food) throws AnimalException {
    this.animal = animal;
    if (findWord(animal, "wolf")) {
        throw new AnimalException("This animal is a predator.");
    }
    else {
        this.food = food;
    }
}

void foo() {
    Zoo myZoo;
    try {
        myZoo  = new Zoo("wolf", "meat");
    } catch (AnimalException ex) {
        System.out.println(ex.toString())
    }
    // myZoo is still null, uninitialized.
}
Run Code Online (Sandbox Code Playgroud)

但是,如果您希望有掠食者Zoo,但同时向所有访客发出警告,则应该只显示一些警告。

public Zoo (String animal, String food) throws AnimalException {
    this.animal = animal;
    this.food = food;
    if (findWord(animal, "wolf")) {
        System.out.println("Beware, we have a predator in zoo");
    }
}
Run Code Online (Sandbox Code Playgroud)

另外,您是否知道您的食物中Zoo可能只含有一种动物和一种食物?

还有一件事。你的方法findWord(String, String)太复杂了。Java包含很多有用的类和函数,这样我们就不会一次又一次地耽误自己编写代码。查找单词的子串是非常有用且最喜欢的功能。看一眼indexOf(String)。它是专门为您的目的而设计的,并且可能以类似的方式实现。