- /**
- 一个长方形和一个圆形, 求面积. 如果如果参数出现负数,则认为是异常, 运算无结果
- */
- class AreaException extends RuntimeException //继承运行时错误的自定义异常, 面积异常
- {
- AreaException (String msg)
- {
- super(msg);
- }
- }
- abstract class Shape //长方形和圆形父类, 包含求面积的抽象方法
- {
- abstract void getarea();
- }
- class Rectangle extends Shape //长方形类
- {
- private int len,wid;
- Rectangle (int len, int wid) //构造函数中为长方形对象赋值长和宽特性
- {
- if (len<=0 || wid<=0)
- {
- throw new AreaException("长宽参数不正确,面积无法运算"); // 如果参数不正确, 则抛出运行时异常对象
- }
- this.len= len;
- this.wid= wid;
- }
- void getarea()
- {
- System.out.println(len*wid);
- }
- }
- class Circle extends Shape //圆形类
- {
- private int radius;
- Circle(int radius)
- {
- if(radius <= 0) //构造函数中为圆形对象赋值半径特性
- throw new AreaException("半径参数不正确,面积无法运算");
- this.radius = radius;
- }
- void getarea()
- {
- System.out.println(3.14*radius*radius);
- }
- }
- class ExceptionTest
- {
- public static void main(String[] args)
- {
- Shape a = new Rectangle(2,5);
- a.getarea();
- a = new Circle(0);
- a.getarea();
- }
- }
复制代码 自己写代码过程中犯的错误
1. 把abstract class 写成了abstract interface
2. 把创建对象Shape a = new Rectangle(2,5);中的参数写到了调用方法a.getarea();中
3. throw new AreaException(); 语句里漏写new
4. AreaException (String msg) 语句漏写参数类型String
|
|