在构造函数中捕获异常

阿尔文·莱皮克(Alvin Lepik)
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;
        }
}

我想做的是,当awolf被构造函数捕获时,for的值food会自动更改为其他值。我确实尝试使用getter-setters,但是出现的错误unreachable code我该怎么办?

泽雷格斯

设计的问题是,校准会throw exception离开块的范围,正在寻找try-catch可以处理异常的块。就你而言

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

如果在构造函数中引发异常,并且该异常离开了函数,因为在构造函数中没有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.
}

但是,如果您希望在中存在捕食者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");
    }
}

另外,您是否知道自己Zoo可能只包含一种动物和一种食物?

还有一件事。您的方法findWord(String, String)太复杂了。Java包含许多有用的类和函数,因此我们不会一次又一次地延迟编写代码。寻找单词的子串是非常有用和喜欢的功能。看一看indexOf(String)它是专为您的目的而设计的,并且可能以类似的方式实现。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章