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] 删除。
我来说两句