Java Reference
In-Depth Information
24 result += list[i];
25
return
result;
26 }
27 }
14.4.5 Example: Declaring, Throwing, and Catching Exceptions
This example demonstrates declaring, throwing, and catching exceptions by modifying the
setRadius
method in the
Circle
class in Listing 8.9, CircleWithPrivateDataFields.java.
The new
setRadius
method throws an exception if the radius is negative.
Listing 14.7 defines a new circle class named
CircleWithException
, which is the same
as
CircleWithPrivateDataFields
except that the
setRadius(double newRadius)
method throws an
IllegalArgumentException
if the argument
newRadius
is negative.
L
ISTING
14.7
CircleWithException.java
1
public class
CircleWithException {
2
/** The radius of the circle */
3
private double
radius;
4
5
/** The number of the objects created */
6
private static int
numberOfObjects =
0
;
7
8
/** Construct a circle with radius 1 */
9
public
CircleWithException() {
10
this
(
1.0
);
11 }
12
13
/** Construct a circle with a specified radius */
14
public
CircleWithException(
double
newRadius) {
15
16 numberOfObjects++;
17 }
18
19
setRadius(newRadius);
/** Return radius */
20
public double
getRadius() {
21
return
radius;
22 }
23
24
/** Set a new radius */
25
public void
setRadius(
double
newRadius)
26
throws
IllegalArgumentException
{
declare exception
27
if
(newRadius >=
0
)
28 radius = newRadius;
29
else
throw new
IllegalArgumentException(
30
31
32 }
33
34
throw exception
"Radius cannot be negative"
);
/** Return numberOfObjects */
35
public static int
getNumberOfObjects() {
36
return
numberOfObjects;
37 }
38
39
/** Return the area of this circle */
40
public double
findArea() {
41
return
radius * radius *
3.14159
;
42 }
43 }