- class NovalueException extends RuntimeException
- {
- NovalueException(String message)
- {
- super(message);
- }
- }
- interface Shape
- {
- void getArea();
- }
- class Rec implements Shape
- {
- private double length,width;
- Rec(double length, double width)
- {
- if(length<=0 || width<=0)
- throw new NovalueException("出现非法的值");
- this.length = length;
- this.width = width;
- }
- public void getArea()
- {
- System.out.println("Area="+length * width);
- }
- }
- class Cir implements Shape
- {
- private double radius;
- public static final double PI = 3.14;
- Cir(double radius)
- {
- if (radius<=0)
- throw new NovalueException("出现非法的值");
- this.radius = radius;
- }
- public void getArea()
- {
- System.out.println("Area="+radius * radius * PI);
- }
- }
- class ExceptionDemo
- {
- public static void main(String[] args)
- {
- Rec r = new Rec(-2.5,3.9);
- r.getArea();
- Cir c = new Cir(3.0);
- c.getArea();
-
- System.out.println("over");
- }
-
- }
复制代码
想问我这个程序如果Rec里面出现负值了,下面的Cir就算没有负值,也检测不到,只会直接报出异常终止程序,有什么好的解决方法 两个类之间的执行不会影响到彼此 |
|