繁体   English   中英

Java异常构造函数和方法

[英]Java Exceptions constructor & methods

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

  • 构造函数。 接受直角三角形的边作为参数。 当一条或两条腿设置为 0 或负数时,构造函数抛出非法参数异常
  • setLegA(), setLegB() - mutator 方法。 当 leg 设置为 0 或负数时,这两种方法都会抛出 Illegal Argument Exception。
  • 具有处理非法参数异常的 try/catch 块。 确保在 main() 中编写调用 Illegal Argument Exception 的调用。 此外,请确保调用带有错误参数的类构造函数和 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());
        }

你可以改变你的代码

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM