A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© 边情2015 中级黑马   /  2015-10-1 20:36  /  280 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

有一个长方形和圆形,获取面积时,对于面积如果出现非法数值时,视为获取面积出现错误。问题通过异常来表示。
  1. class NoValueException extends RuntimeException
  2. {
  3.         NoValueException(String msg)
  4.         {
  5.                 super(msg);
  6.         }
  7. }
  8. interface Shape
  9. {
  10.         public abstract double getArea();
  11. }
  12. class Rec implements Shape
  13. {
  14.         private double a,b;

  15.         Rec(double a,double b)        throws NoValueException
  16.         {       
  17.                 if(a<=0 || b<=0)
  18.                         throw new NoValueException("出错了");               
  19.                 this.a = a;
  20.                 this.b = b;                
  21.         }
  22.         public double getArea()
  23.         {
  24.                 return a*b;
  25.         }
  26. }

  27. class Cir implements Shape
  28. {
  29.         private double r;
  30.         private static final double pi=3.14;
  31.         Cir(double r)
  32.         {
  33.                 if(r<=0)
  34.                         throw new NoValueException("出错了");//NoValueException 继承了RuntimeException,在这里不用抛出
  35.                 this.r = r;
  36.         }
  37.         public double getArea()
  38.         {
  39.                 return r*r*pi;
  40.         }

  41. }
  42. class  ExceptionTest1
  43. {
  44.         public static void main(String[] args)
  45.         {               
  46.                 try
  47.                 {
  48.                         Rec ab = new Rec(-3,4);
  49.                         System.out.println(ab.getArea());
  50.                 }
  51.                 catch (NoValueException e)
  52.                 {
  53.                         System.out.println(e.toString());
  54.                 }
  55.                
  56.                 System.out.println("Get Rec area over");//抛出的异常有try_catch掉 所以程序继续执行后面的语句
  57.                 Cir c = new Cir(-2.5);               
  58.                 System.out.println(c.getArea());//由于抛出的异常为RuntimeException类开 因此程序执行到这里会停止,等待改证。(异常出现没法运算,这种情况就是RuntimeException类型)
  59.                 System.out.println("Cir Rec area over");
  60.         }
  61. }
复制代码

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马