[英]Java Exceptions constructor & methods
我试图在我写的类中抛出异常。 我还在主类中使用了 try/catch 块。 我想显示特定异常(legA 或 legB)的消息。 但它只给我一条常见错误的消息,而不是关于什么腿值无效的信息。 怎么了? 这是作业详情:
.
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.