- /*
- 异常小练习:
- 需求:
- 有一个圆形和长方形。
- 都可以获取面积,对于面积如果出现非法的数值,视为是面积出现问题。
- 思路:
- 1.都要实现面积方法,且实现方式不同,
- 2.自定义一个异常类用于检测面积出现问题
- */
- /*异常面积类:*/
- class AreaCountException extends Exception
- {
- AreaCountException(String str)
- {
- super(str);
- }
- }
- //面积接口
- interface Inner
- {
- double getArea();
- }
- //圆类
- class Circle implements Inner
- {
- public static final double PI=3.14;
- private double r;
- Circle(double r)
- {
- this.r=r;
- }
- public double getArea() throws AreaCountException
- {
- if(r>0)
- return (PI*r*r);
- else throw new AreaCountException("面积小于0");
- }
- }
- //长方形类
- class Rectangles implements Inner
- {
- private double width;
- private double longth;
- Rectangles(double width,double longth)
- {
- this.width=width;
- this.longth=longth;
- }
- public double getArea() throws AreaCountException
- {
- if(width>0&&longth>0)
- return (width*longth);
- else
- throw new AreaCountException("面积小于0");
- }
- }
- class AreaException
- {
- public static void main(String[] args)
- {
- Circle cir=new Circle(-3.2);
- Rectangles rec=new Rectangles(4.2,-3);
- try
- {
- System.out.println("circle area="+cir.area());
- }
- catch (AreaCountException e)
- {
- System.out.println(e.toString());
- System.out.println("circle areaCountException");
- }
- try
- {
- System.out.println("rectangle area="+rec.area());
- }
- catch (AreaCountException e)
- {
- System.out.println(e.toString());
- System.out.println("rectangle areaCountException");
- }
- }
- }
复制代码
|