gpt4 book ai didi

java - 为什么Java方法在测试类中不抛出异常?

转载 作者:行者123 更新时间:2023-11-30 07:26:36 25 4
gpt4 key购买 nike

为什么我不能从 Mammal 对象中的 takeDamage 方法抛出异常并在创建该对象的 Test 类中捕获它?

    package animals;
public class Mammal extends Animal{
public final boolean predation, herbivory;
public String hairColor;

public Mammal() {
super();
this.predation = rand.nextBoolean();
this.herbivory = rand.nextBoolean();
this.hairColor = colors[rand.nextInt(8)];
}

public Mammal(boolean predation, boolean herbivory, String hairColor) {
super();
this.predation = predation;
this.herbivory = herbivory;
this.hairColor = hairColor;
}
public Mammal(boolean predation, boolean herbivory, String hairColor, String name, boolean sex) {
super(name, sex);
this.predation = predation;
this.herbivory = herbivory;
this.hairColor = hairColor;
}

public void takeDamage(int damage) throws TakeDamageException{
if(damage < 1) {
throw new TakeDamageException("Damage cant be negative!");
}
else this.health -= damage;
}

我 try catch takeDamage 方法抛出的异常,但我得到:异常 TakeDamageException is never throw in the body of相应的 try 语句

并且:未报告的异常TakeDamageException;必须被捕获或宣布被扔出 哺乳动物.takeDamage(-123);

 import animals.*;

public class Test extends Mammal {

public static void main(String[] args){
Mammal mammal = new Mammal();
System.out.println(mammal.doDamage());
System.out.println(mammal.getEnergy());
try {
mammal.takeDamage(-123);
}
catch(TakeDamageException e) {
System.out.println("Couldnt take damage:" + e);
}
}
}

将我的异常类定义为:

public class TakeDamageException extends Exception {
public TakeDamageException(String message) {
super(message);
}
public TakeDamageException() {
}
}

最佳答案

一个更简洁的例子就可以了。我不同意测试应该从哺乳动物继承,但将其保留在我的示例中:

哺乳动物.java:

public class Mammal {
int health =500;
public void takeDamage(int damage) throws Exception{
if(damage < 1) {
throw new Exception("Damage cant be negative!");
}
else this.health -= damage;
}

}

测试.java:

public class MTest extends Mammal {
public static void main(String args[]) {
Mammal m = new Mammal();
try {
m.takeDamage(-100);
} catch(Exception e) {
System.out.println("Exception");
}
}

}

您可能一次尝试做太多事情。婴儿学步。

关于java - 为什么Java方法在测试类中不抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36750186/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com