有一个长方形和圆形,获取面积时,对于面积如果出现非法数值时,视为获取面积出现错误。问题通过异常来表示。
- class NoValueException extends RuntimeException
- {
- NoValueException(String msg)
- {
- super(msg);
- }
- }
- interface Shape
- {
- public abstract double getArea();
- }
- class Rec implements Shape
- {
- private double a,b;
- Rec(double a,double b) throws NoValueException
- {
- if(a<=0 || b<=0)
- throw new NoValueException("出错了");
- this.a = a;
- this.b = b;
- }
- public double getArea()
- {
- return a*b;
- }
- }
- class Cir implements Shape
- {
- private double r;
- private static final double pi=3.14;
- Cir(double r)
- {
- if(r<=0)
- throw new NoValueException("出错了");//NoValueException 继承了RuntimeException,在这里不用抛出
- this.r = r;
- }
- public double getArea()
- {
- return r*r*pi;
- }
- }
- class ExceptionTest1
- {
- public static void main(String[] args)
- {
- try
- {
- Rec ab = new Rec(-3,4);
- System.out.println(ab.getArea());
- }
- catch (NoValueException e)
- {
- System.out.println(e.toString());
- }
-
- System.out.println("Get Rec area over");//抛出的异常有try_catch掉 所以程序继续执行后面的语句
- Cir c = new Cir(-2.5);
- System.out.println(c.getArea());//由于抛出的异常为RuntimeException类开 因此程序执行到这里会停止,等待改证。(异常出现没法运算,这种情况就是RuntimeException类型)
- System.out.println("Cir Rec area over");
- }
- }
复制代码 |
|