- package practice;
- /**
- * 异常练习:
- * 需求:求圆和长方形的面积,针对非法数据,用异常描述。
- * @author Qihuan
- *
- */
- class NoValueException extends RuntimeException {
- public NoValueException(String msg) {
- // TODO Auto-generated constructor stub
- super(msg);
- }
- }
- interface sharp {
- double getArea();
- }
- class Rectangle implements sharp {
- private double length, width;
-
- public Rectangle(double length, double width) {
- // TODO Auto-generated constructor stub
- if (length <= 0 || width <= 0)
- throw new NoValueException("长宽非法!");
-
- this.length = length;
- this.width = width;
- }
- @Override
- public double getArea() {
- // TODO Auto-generated method stub
- return length*width;
- }
-
- }
- class Circle implements sharp {
- public static final double PI = 3.14;
- private double radius;
-
- public Circle(double radius) {
- // TODO Auto-generated constructor stub
- if (radius <= 0)
- throw new NoValueException("半径非法!");
-
- this.radius = radius;
- }
-
- @Override
- public double getArea() {
- // TODO Auto-generated method stub
- return radius*radius*PI;
- }
- }
- public class ExceptionTest {
- public static void main(String[] args) {
- System.out.println("长方形的面积:");
- Rectangle r = new Rectangle(-2, 5);
- System.out.println(r.getArea());
-
- System.out.println("圆的面积:");
- Circle c = new Circle(0);
- System.out.println(c.getArea());
- }
- }
复制代码
|
|