Java Reference
In-Depth Information
Example of a realistic try-statement
In Fig. 10.6, we present a function that catches two types of errors: a sub-
script out of range and an attempt to convert a
String
that does not contain an
integer into an
int
. Class
JLiveWindow
, which provides a GUI with some
int
fields into which a user is expected to type integers, provides the motivation for
this example. Take a look at the code in that class to see a real use of exception
handling.
The body of the try-statement in Fig. 10.6 converts the value of b[f] —a
String
— to an
int
and returns it. This return statement is enclosed in a try-
block because its execution may cause two kinds of
Exception
: a subscript out
of range and a
NumberFormatException
, which may be thrown by method
parseInt
. Both of these exceptions are caught by catch clauses. This example
shows that a try-statement may have any number of catch clauses, not just one.
We could have used an if-statement to test whether
f
was in the subscript
range of array
b
. Here, catching it using a try-statement leads to a simpler, more
consistent method body since the try-statement has to be used anyway to catch
the second kind of object that could be thrown.
Activities 10-
3.2 and 10.3.3
describe try-
statements in
JLiveWindow
and JLiveRead.
Get the pro-
grams from
page 10-3.
10.4.3
Propagation of a thrown exception
We explain the throwing of an object. The program of Fig. 10.7 contains three
methods. Suppose it is executed, by calling method
main
. Method
main
calls
method
first
, which then calls method
second
.
Now suppose that an object
ob
is thrown within method
second
, signaling
some sort of error, and that the throw does not occur within a try-block. Since
there is no catch clause to catch the object, it is thrown further,
to the calling
method
. Thus, in this example, it appears that the call on method
second
throws
ob
. And if this call on method
second
does not appear within a try-block, object
ob
is thrown out further, to calling method
main
. So it looks like method call
Activity 10-3.4
makes this ma-
terial more
accessible.
public class
C {
public static void
main(String[] args) {
try
{
first();
}
catch
( ... )
{ ... }
}
public static void
first()
{ second(); }
public static void
second()
{ ... }
}
Figure 10.7:
Propagating a thrown exception
Search WWH ::
Custom Search