需求:要求写一个求圆和长方形的面积。
要有异常处理机制。(出现零和负数。)
package 异常练习;
public class NegativeException extends RuntimeException
{
//继承RunTimeException而不继承Exception的原因:
//因为如果传入的值是非法值,如果程序里的圆面积和长方形面积接下来要作其他操作,
//那么就必须要让程序停下来,不然后续的会出问题。不能处理的问题,应该通过修正代码解决。
public NegativeException(String msg)
{
super(msg);
}
}
package 异常练习;
public class ZeroException extends RuntimeException
{
public ZeroException(String msg)
{
super(msg);
}
}
package 异常练习;
public interface Area {
//用接口而不是用抽象类的原因:
//因为面积不一定是图形的属性,可以是附加的属性。
public double getArea();
}
package 异常练习;
public class circle implements Area
{
private int radius;
public circle(int radius)
{
//原先把异常对象放在getArea方法内,
//其实应该放在构造函数里,如果传入的值非法,
//那么圆形就不应该建立对象这样才符合逻辑。
if(radius<0) throw new NegativeException("半径不能为负数");
if(radius==0)throw new ZeroException("半径不能为0");
this.radius= radius;
}
public static final double PI =3.14;
public double getArea()
{
return radius*PI;
}
}
package 异常练习;
public class rectangle implements Area
{
private int length,width;
public rectangle(int length ,int width)
{
if(length<0||width <0) throw new NegativeException("长宽不能小于零");
if(length==0||width==0)throw new ZeroException("长宽不能为零");
this.length=length;
this.width=width;
}
public double getArea()
{
//if(length<0||width <0)
//if(length==0||width==0)
//不要把问题在程序流程里处理,而应把问题与程序正常流程分离,以提高阅读性。
//否则流程代码与问题处理代码结合过于紧密,高耦合,阅读性差。
return length*width;
}
}
package 异常练习;
public class ExceptionPractice {
public static void main(String[] args) {
circle cir= new circle(0);
System.out.println(cir.getArea());
rectangle rtg = new rectangle(-3,4);
System.out.println(rtg.getArea());
}
}