Java Reference
In-Depth Information
return array[index+2];
This statement is outside the
try
block, so the exception is not caught. The exception is therefore thrown
by the method when it is called in
main()
. However, you aren't obliged to declare that the
divide()
method throws this exception because the
ArrayIndexOutOfBoundsException
class is a subclass of
RuntimeException
and is therefore exempted from the obligation to deal with it.
The
main()
method has two
try
blocks. The first
try
block encloses three calls to the
divide()
method.
The first call executes without error; the second call causes an arithmetic exception in the method; and
the third call causes an index-out-of-bounds exception. There are two
catch
blocks for the first
try
block
in
main()
to deal with these two potential exceptions.
The
read()
method in the second
try
block in
main()
can cause an I/O exception to be thrown. Because
this is one of the exceptions that the compiler checks for, you must either put the statement that calls the
read()
method in a
try
block and have a
catch
block to deal with the exception or declare that
main()
throws the
IOException
exception. If you don't do one or the other, the program does not compile.
Using the
read()
method in this way has the effect of pausing the program until the Enter key is pressed.
You look at
read()
, and other methods for I/O operations in the next four chapters. The
IOException
class is in the package
java.io
, so you need the
import
statement for this class because you refer to it
in the
catch
block using its unqualified name. Of course, if you referred to it as
java.io.IOException
,
you would not need to import the class name. Remember that only classes defined in
java.lang
are in-
cluded in your program automatically.
Normal Execution of a Method
The first line of output from the
TryBlockTest
example indicates that execution of the
try
block in
main()
has begun. The next block of output from the example is the result of a straightforward execution of the
divide()
method:
First try block in divide() entered
Code at end of first try block in divide()
finally block in divide()
result = 2
No exceptions occur in
divide()
, so no
catch
blocks are executed.
The code at the end of the
divide()
method, following the
catch
blocks, isn't executed because the
return
statement in the
try
block ends the execution of the method. However, the
finally
block in
di-
vide()
is executed before the return to the calling method occurs. If you comment out the
return
statement
at the end of the
divide()
method's
try
block and run the example again, the code that follows the
fi-
nally
block is executed.
The sequence of execution when no exceptions occur is shown in
Figure 7-3
.