2021-01-04

package ldz;
public class Circle {
    private double radius;

    public double getRadius() {
        return radius;
    }

    public void setRadius(double radius) throws CircleException {
        if(radius<0){
            throw new CircleException(radius);
        }
        else;this.radius = radius;
        
    }
    public void show(){
        System.out.println("area="+3.14*radius*radius);
    }
    

}

package ldz;

public class CircleException extends Exception {
    private double radius;

    public CircleException(double radius) {
        super();
        this.radius = radius;
    }

    @Override
    public String toString() {
        return "radius:r="+radius+",needs to be a positive number.";
    }
    
    
    
    

}

package ldz;

public class TestException {

    public static void main(String[] args) {
        Circle c= new Circle();
        try{
            c.setRadius(-2.0);
            }
        catch(Exception e){
            System.out.println("Custom exception:"+e.toString()+"");
            }
        c.show();
        

    }

}
  

你可能感兴趣的:(2021-01-04)