Java Reference
In-Depth Information
24 result += list[i];
25
return result;
26 }
27 }
12.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 9.8, CircleWithPrivateDataFields.java.
The new setRadius method throws an exception if the radius is negative.
Listing 12.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 12.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 setRadius(newRadius);
16 numberOfObjects++;
17 }
18
19
/** 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 {
27 if (newRadius >= 0 )
28 radius = newRadius;
29
declare exception
else
30
throw new IllegalArgumentException(
throw exception
31
"Radius cannot be negative" );
32 }
33
34
/** 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 }
 
 
Search WWH ::




Custom Search