- /*
- 定义一个圆和长方形,获取他们的面积,若面积出现负值则代表出现问题,
- 问题用异常来表示。程序写之前先设计。
- */
- class NoValueException extends RuntimeException//自定义异常
- {
- NoValueException(String msg)
- {
- super(msg);
- }
- }
- interface Shape//定义接口
- {
- void getArea();
- }
- class Rec implements Shape//实现接口,定义长方形
- {
- private int len,wid;
- Rec(int len,int wid)//构造函数初始化
- {
- if(len<=0||wid<=0)//throws NoValueException
- throw new NoValueException("出现错误!");
-
- this.len = len;
- this.wid = wid;
- }
- public void getArea()//重写接口中的方法
- {
- System.out.println(len*wid);
- }
- }
- class Circle implements Shape//定义圆
- {
- private int radius;
- public static final double PI=3.14;
- Circle(int radius)
- {
- if(radius<=0)
- throw new NoValueException("圆的半径不能是负值啦");
- this.radius=radius;
- }
- public void getArea()
- {
- System.out.println(radius*radius*PI);
- }
- }
- class zzy
- {
- public static void main(String[]args)
- {
- //Circle c=new Circle(-3);
- //c.getArea();
-
- Rec r=new Rec(-4,5);
- r.getArea();
-
- System.out.println("12345678");
- }
- }
复制代码
备注:异常的一个练习 |
|