Java Reference
In-Depth Information
A test program that uses the new
Circle
class is given in Listing 14.8.
L
ISTING
14.8
TestCircleWithException.java
1
public class
TestCircleWithException {
2
public static void
main(String[] args) {
3
4 CircleWithException c1 =
new
CircleWithException(
5
);
5 CircleWithException c2 =
new
CircleWithException(
-5
);
6 CircleWithException c3 =
new
CircleWithException(
0
);
7
8
9 System.out.println(ex);
10
11
12 System.out.println(
"Number of objects created: "
+
13 CircleWithException.getNumberOfObjects());
14 }
15 }
try
{
try
}
catch
(IllegalArgumentException ex) {
catch
}
java.lang.IllegalArgumentException: Radius cannot be negative
Number of objects created: 1
The original
Circle
class remains intact except that the class name is changed to
CircleWithException
, a new constructor
CircleWithException(newRadius)
is
added, and the
setRadius
method now declares an exception and throws it if the radius is
negative.
The
setRadius
method declares to throw
IllegalArgumentException
in the method
header (lines 25-32 in CircleWithException.java). The
CircleWithException
class would
still compile if the
throws IllegalArgumentException
clause were removed from the
method declaration, since it is a subclass of
RuntimeException
and every method can
throw
RuntimeException
(an unchecked exception) regardless of whether it is declared in
the method header.
The test program creates three
CircleWithException
objects—
c1
,
c2
, and
c3
—to test
how to handle exceptions. Invoking
new CircleWithException(-5)
(line 5 in Listing 14.8)
causes the
setRadius
method to be invoked, which throws an
IllegalArgumentException
,
because the radius is negative. In the
catch
block, the type of the object
ex
is
IllegalArgumentException
, which matches the exception object thrown by the
setRadius
method, so this exception is caught by the
catch
block.
The exception handler prints a short message,
ex.toString()
(line 9 in Listing 14.8),
about the exception, using
System.out.println(ex)
.
Note that the execution continues in the event of the exception. If the handlers had not
caught the exception, the program would have abruptly terminated.
The test program would still compile if the
try
statement were not used, because the method
throws an instance of
IllegalArgumentException
, a subclass of
RuntimeException
(an
unchecked exception). If a method throws an exception other than
RuntimeException
or
Error
, the method must be invoked within a
try-catch
block.
14.9
What is the purpose of declaring exceptions? How do you declare an exception, and
where? Can you declare multiple exceptions in a method header?
14.10
What is a checked exception, and what is an unchecked exception?
14.11
How do you throw an exception? Can you throw multiple exceptions in one
throw
statement?
14.12
What is the keyword
throw
used for? What is the keyword
throws
used for?
✓
✓
Check
Point