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/