Java Reference
In-Depth Information
ception2
in the first
catch
block. The second
catch
block is executed for exceptions of type
MyExcep-
tion3
. The method can also throw two other types of exceptions that are not caught within the method, and
these are identified in the
throws
clause that follows the parameter list for the method. The code in the
fi-
nally
block always gets executed, regardless of whether an exception is thrown or not.
In many cases, a method needs only a single
try
block followed by all the
catch
blocks for the excep-
tions that need to be processed in the method, perhaps followed by a
finally
block. Java, however, gives
you the flexibility to have as many
try
blocks as you want. This makes it possible for you to separate vari-
ous operations in a method by putting each of them in their own
try
block — an exception thrown as a
result of a problem with one operation does not prevent subsequent operations from being executed.
Execution Sequence
You saw how the sequence of execution proceeds with the simple case of a
try
block and a single
catch
block. Let's explore the sequence in which code executes when you have the
try
-
catch
-
finally
combin-
ations of blocks, when different exceptions are thrown. This is easiest to comprehend by considering an ex-
ample. You can use the following code to create a range of exceptions and conditions.
TRY IT OUT: Execution Sequence of a try Block
It is convenient, in this example, to use an input statement to pause the program. The method you
use can throw an exception of a type defined in the
java.io
package. You start by importing the
java.io.IOException
class name into the source file. Give the class that contains
main()
the name
TryBlockTest
. You define another method,
divide()
, in this class that is called in
main()
. The overall
structure of the
TryBlockTest
class source file is: