Write a program to create a class CirclesWithException with the following information:
radius in double with private access specifier.
class CirclesWithException {
private double radius;
/**
* a constructor to pass on radius of a Circle. Call setRadius() method to set
* the radius of circle inside the constructor.
*
* @param radius
*/
public CirclesWithException(double radius) {
setRadius(radius);
}
/**
* @return the radius
*/
public double getRadius() {
return radius;
}
/**
* @param radius the radius to set
*/
public void setRadius(double radius) {
if (radius < 0) {
throw new IllegalArgumentException("The argument radius is negative.");
}
this.radius = radius;
}
public void printRadius() {
System.out.println("Radius: " + radius);
}
}
public class App {
/**
* The start point of the program
*
* @param args
*
*/
public static void main(String[] args) {
// CirclesWithException with positive, negative and zero
try {
CirclesWithException positive = new CirclesWithException(5);
positive.printRadius();
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
try {
CirclesWithException negative = new CirclesWithException(-5);
negative.printRadius();
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
try {
CirclesWithException zero = new CirclesWithException(0);
zero.printRadius();
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
Comments
Leave a comment