有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java异常构造函数和方法

我试图在我编写的类中抛出异常。我还在主类中使用try/catch块。我想显示特定异常(legA或legB)的消息。但它只给了我一个关于常见错误的信息,而不是什么leg值无效的信息。发生了什么? 以下是作业详情:

  • 构造器。接受直角三角形的腿作为参数。当一个或两个分支设置为0或负数时,构造函数引发非法参数异常
  • setLegA(),setLegB()-mutator方法。当leg设置为0或负数时,这两种方法都会引发非法参数异常
  • 具有处理非法参数异常的try/catch块。确保在main()中编写调用非法参数异常的调用。此外,请确保使用错误参数调用类构造函数和mutator方法,以展示异常抛出/捕获的作用

package righttriangle;
/**
 *
 * @author Liliya Sherstobitova
 */
public class RightTriangle {

   private double legA; // hold  legA length value
   private double legB; // hold  legB length value

   public RightTriangle()
   {
       legA = 0; // set start value
       legB = 0; // set start value
    }

   /**
    * constructor
    * @param a is legA length
    * @param b is legB length
    */
   public RightTriangle(double a, double b)
   {
       legA = a;
       legB = b;

       if (a<=0 || b<=0)
       {
           throw new IllegalArgumentException ("Leg length cannot be negative");
       }
   }

   /**
    * method setLegA stores value in legA field
    * @param a is legA length
    * @throws IllegalArgumentException 
    */
   public void setLegA(double a) throws IllegalArgumentException
   {
       if (a<=0.0) 
       {
           throw new IllegalArgumentException ("Leg length "+a+"cannot be negative");
       }
       this.legA = a;

   }
 /**
    * method getLegA  returns a RightTriangle object's length.
    * @return the value in the legA field
    */
   public double getLegA()
   {
       return legA;
   }
}

***
piece of code from main
  try
        {
        // Test2        
        box = new RightTriangle(-5.0, 1.5);     
        System.out.println("Test 2");
        System.out.println("Right tringle legA = " + box.getLegA());
        System.out.println("Right tringle legB = " + box.getLegB());
        System.out.println("Right tringle Hypotenuse = " + box.getHypotenuse());
        System.out.println("Right tringle Area = " + box.GetArea());
        System.out.println("Right tringle Perimeter = " + box.getPerimeter());
        System.out.println();
        }
        catch (IllegalArgumentException e)
        {
            System.out.println(e.getMessage());
        }

共 (1) 个答案

  1. # 1 楼答案

    您可以更改代码

       if (a<=0 || b<=0)
       {
           throw new IllegalArgumentException ("Leg length cannot be negative");
       }
    

      if (a<=0)
       {
           throw new IllegalArgumentException ("Leg A length cannot be negative");
       }
      if (b<=0)
       {
           throw new IllegalArgumentException ("Leg B length cannot be negative");
       }