Java Reference
In-Depth Information
}
TryBlockTest.java
Because the
read()
method for the object
in
(this object represents the standard input stream and com-
plements the
out
object, which is the standard output stream) can throw an I/O exception, it must be
called in a
try
block and have an associated
catch
block, unless you choose to add a
throws
clause to
the header line of
main()
.
If you run the example, it produces the following output:
First try block in main() entered
First try block in divide() entered
Code at end of first try block in divide()
finally block in divide()
result = 2
First try block in divide() entered
Arithmetic exception caught in divide()
index = 0 Expression: array[0]/array[1] is 10/0
finally block in divide()
Executing code after try block in divide()
result = 2
First try block in divide() entered
Index-out-of-bounds exception caught in divide()
array length = 3 index = 1
finally block in divide()
Executing code after try block in divide()
Index-out-of-bounds exception caught in main()
Outside first try block in main()
Press Enter to exit
In second try block in main()
finally block for second try block in main()
How It Works
All the
try
,
catch
, and
finally
blocks in the example have output statements so you can trace the se-
quence of execution. Note that the
finally
block is executed, whatever happens in the
divide()
meth-
od, even when the normal return is executed in the
try
block in
divide()
.
Within the
divide()
method, the code in the
try
block can throw an
ArithmeticException
if the ele-
ment
array[index+1]
of the array passed to it is 0. It can also throw an
ArrayIndexOutOfBoundsEx-
ception
in the
try
block if the index value passed to it is negative, or it results in
index+2
being beyond
the array limits. Both these exceptions are caught by one or other of the
catch
blocks, so they are not
apparent in the calling method
main()
.
Note, however, that the last statement in
divide()
can also throw an
ArrayIndexOutOfBoundsExcep-
tion
: