为什么Java方法不会在测试类中引发异常?

时间:2016-04-20 16:46:13

标签: java exception

为什么我不能在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;
      }

我尝试捕获takeDamage方法引发的异常,但是我得到:异常TakeDamageException永远不会在相应的try语句的主体中抛出

和:未报告的异常TakeDamageException;必须被抓住或宣布被抛出        mammal.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() {
  }
}

2 个答案:

答案 0 :(得分:1)

一个更简洁的例子可以正常工作。我不同意测试应该从Mammal继承,但是留在那里为我的例子:

Mammal.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;
  }

}

Test.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");
    }
}

}

你可能一次尝试做太多。宝贝步骤。

答案 1 :(得分:0)

您可能有一个潜在的问题:从静态上下文引用非静态方法takeDamage(int)。即使您在Mammal的子类中工作,也需要引用它的实例来使用该方法。