Illegal argument exception on java

youko :

i am new in java and trying to learn about exception handling so my code is like this

public class CircleWithException {
private double radius;
private static int numberOfObjects = 0;

public CircleWithException (){
    this(1.0);
}

public CircleWithException (double newRadius){
    setRadius(newRadius);
    numberOfObjects++;
}

public double getRadius(){
    return radius;
}

public void setRadius(double newRadius) throws IllegalArgumentException {
    if(radius>=0) radius = newRadius;
    else if(radius<0)
        throw new IllegalArgumentException("Radius cannot be negative");
}

public static int getNumberOfObjects(){
    return numberOfObjects;
}

public double findArea(){
    return radius*radius*Math.PI;
}

and the main method is like this

public class ApplicationCircle {
public static void main(String[] args){
    try{
        CircleWithException  c1 = new CircleWithException (5);
        CircleWithException  c2 = new CircleWithException (-5);
        CircleWithException  c3 = new CircleWithException (0);
    }

    catch (IllegalArgumentException ex){
        System.out.println(ex);
    }

    System.out.println("Number of objects created: "+CircleWithException .getNumberOfObjects());
}

but instead of an error i get this result

"Number of objects created: 3"

can anyone help me? Thank you very much

jetspiking :

Your code is written correctly, however it looks like you made a mistake in the "setRadius(double newRadius)" method. You are checking whether radius is smaller than 0 (or >=0), but since it is never set in the case of -5, you won't throw the exception.

I believe you want to check if newRadius is bigger or smaller than 0 instead.

So the code would be (note how radius is changed to newRadius, since that is the argument you are passing in your method):

public void setRadius(double newRadius) throws IllegalArgumentException {
if(newRadius>=0) radius = newRadius;
else if(newRadius<0)
    throw new IllegalArgumentException("Radius cannot be negative"); }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=12117&siteId=1