Java Reference
In-Depth Information
printStackTrace() ) in Exception are inherited from Throwable . The Exception
class contains four constructors. Among them, the following two constructors are often used:
java.lang.Exception
+Exception()
+Exception(message: String)
Constructs an exception with no message.
Constructs an exception with the specified message.
Line 6 invokes the superclass's constructor with a message. This message will be set in the
exception object and can be obtained by invoking getMessage() on the object.
Tip
Most exception classes in the Java API contain two constructors: a no-arg constructor
and a constructor with a message parameter.
To create an InvalidRadiusException , you have to pass a radius. There-
fore, the setRadius method in Listing 12.7 can be modified as shown in Listing 12.11.
L ISTING 12.11
TestCircleWithCustomException.java
1 public class TestCircleWithCustomException {
2
public static void main(String[] args) {
3
try {
4
new CircleWithCustomException( 5 );
5
new CircleWithCustomException( -5 );
6
new CircleWithCustomException( 0 );
7 }
8 catch (InvalidRadiusException ex) {
9 System.out.println(ex);
10 }
11
12 System.out.println( "Number of objects created: " +
13 CircleWithCustomException.getNumberOfObjects());
14 }
15 }
16
17 class CircleWithCustomException {
18
/** The radius of the circle */
19
private double radius;
20
21
/** The number of objects created */
22
private static int numberOfObjects = 0 ;
23
24
/** Construct a circle with radius 1 */
25
public CircleWithCustomException() throws InvalidRadiusException {
declare exception
26
this ( 1.0 );
27 }
28
29 /** Construct a circle with a specified radius */
30 public CircleWithCustomException( double newRadius)
31 throws InvalidRadiusException {
32 setRadius(newRadius);
33 numberOfObjects++;
34 }
35
36
/** Return radius */
37
public double getRadius() {
 
 
Search WWH ::




Custom Search