一个异常处理的习题(是用RunTimeException还是Exception)

需求:要求写一个求圆和长方形的面积。
要有异常处理机制。(出现零和负数。)

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

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值