黑马程序员技术交流社区

标题: 异常处理小练习 [打印本页]

作者: kemeng    时间: 2015-3-13 19:01
标题: 异常处理小练习
  1. /*
  2. 有一个圆形和长方形。都可以获取面积。对于面积如果出现非法的数值,视为是获取面积出现的问题
  3. 问题通过异常来表示
  4. */
  5. interface Shape
  6. {
  7.         void getArea();
  8. }
  9. class NoValueException extends RuntimeException
  10. {
  11.         NoValueException(String message)
  12.         {
  13.                 super(message);
  14.         }
  15. }

  16. class Circle implements Shape
  17. {
  18.         private int radius;
  19.         public static final double NUM=3.14;
  20.         Circle(int radius)
  21.         {
  22.                 if(radius<0)
  23.                         throw new NoValueException("半径不合法");
  24.                 this.radius=radius;
  25.         }
  26.         public void getArea()
  27.         {
  28.                 System.out.println(radius*radius*NUM);
  29.         }
  30. }


  31. class Rec implements Shape
  32. {
  33.         private int len,wid;
  34.         Rec(int len,int wid) //throws NoValueException
  35.         {
  36.                 if( len<=0||wid<=0)
  37.                         throw new NoValueException("数值出现异常");
  38.                 else
  39.                         {
  40.                                 this.len=len;
  41.                                 this.wid=wid;
  42.                         }
  43.         }
  44.         public void getArea()
  45.         {
  46.                 System.out.println(len*wid);
  47.         }
  48. }


  49. class Demo
  50. {
  51.         public static void main(String[] args)
  52.         {
  53.                 //Rec r=new Rec(3,-4);
  54.                 //r.getArea();       
  55.                 //System.out.println("over");
  56.                 Circle c=new Circle(-1);
  57.                 c.getArea();
  58.         }
  59. }
复制代码







欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2