java - 在构造函数中捕获异常

标签 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;
        }
}

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

最佳答案

如果你希望在检测到“狼”时执行一些特定的逻辑,那么异常不是正确的方法。如果在发现“狼”时实例的构造失败,则只应抛出异常。

public Zoo (String animal, String food) {
    this.animal = animal;
    if (findWord(animal, "wolf")) { 
        // put whatever logic you wish here
    }
    else {
        this.food = food;
    }
}

关于java - 在构造函数中捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30366270/

相关文章:

java - 在 Java 中使用 Spark 的 map() 中的条件语句

java - Spring in Action 3 AOP引发问题的例子

java - 生成一个大于或小于前一个随机数的随机数

Java 构造函数参数 Selenium 与 WebDriverBackedSelenium

java - 在 Java 1.4 中如何查看子字符串是否存在于另一个字符串中?

java - 设置请求参数的大小限制

Java代码将字节转换为十六进制

java - 如何从标准中删除标准?

java - 在 SWT 中为列表项创建右键单击选项

Java 正则表达式 : UNGREEDY flag