Page 1 of 1

Task 2: Declaring, throwing and catching exceptions. The example demonstrates declaring, throwing, and catching exceptio

Posted: Sat May 14, 2022 3:34 pm
by answerhappygod
Task 2: Declaring, throwing and catching exceptions.
The example demonstrates declaring,
throwing, and catching exceptions by modifying the setRadius method
in the Circle class. The new setRadius method throws an exception
if the radius is negative.
public class CircleWithException {
/** The radius of the circle */
private double radius;
/** The number of the objects created */
private static int numberOfObjects =
0;
/** Construct a circle with radius 1 */
public CircleWithException()
{
this(1.0);
}
/** Construct a circle with a specified radius
*/
public CircleWithException(double newRadius)
{
setRadius(newRadius);
numberOfObjects++;
}
/** Return radius */
public ……… getRadius()
{
return radius;
}
/** Set a new radius */
public …….. setRadius(double newRadius)
throws ………………….{
if (newRadius >=
0)
radius = newRadius;
else
throw new IllegalArgumentException(
"Radius cannot
be negative");
}
/** Return numberOfObjects */
public static int getNumberOfObjects()
{
return numberOfObjects;
}
/** Return the area of this circle */
public double getArea()
{
return radius * radius *
Math.PI;
}
}
public class TestCircleWithException {
public static void main(String[] args)
{
……………… {
………………… c1 = new …………………(5);
CircleWithException c2 = new CircleWithException(-5);
CircleWithException c3 = new CircleWithException(0);
}
catch (……………………… ex)
{
System.out.println(………………..);
}
System.out.println("Number
of objects created: " +
CircleWithException.getNumberOfObjects());
}
}