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());
}
}
Task 2: Declaring, throwing and catching exceptions. The example demonstrates declaring, throwing, and catching exceptio
-
answerhappygod
- Site Admin
- Posts: 899604
- Joined: Mon Aug 02, 2021 8:13 am
Task 2: Declaring, throwing and catching exceptions. The example demonstrates declaring, throwing, and catching exceptio
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!