Java Reference
In-Depth Information
With this rule of assignment in mind, let's consider the following
try-catch
block:
try {
statement1;
statement2; // Exception of class MyException is thrown here
statement3;
}
catch (Exception1 e1) {
// Handle Exception1
}
catch(Exception2 e2) {
// Handle Exception2
}
When the above snippet of code is executed,
statement2
throws an exception of the
MyException
type.
Suppose the runtime creates an object of
MyException
as follows:
new MyException();
Now the runtime selects the appropriate
catch
block, which can catch the exception object. It starts looking for
the appropriate
catch
clock sequentially starting from the first catch block that is associated with the
try
block. The
process to check if a
catch
block can handle an exception is very simple. Take the parameter type and parameter
name of the catch block and place them to the left of an assignment operator and place the exception object that is
thrown to the right. If the statement thus formed is a valid Java statement, that
catch
block will handle the exception.
Otherwise, the runtime will repeat this check with the next
catch
block.
To check if the first
catch
block can handle the
MyException
in the above snippet of code, Java will form the
following statement:
// Catch parameter declaration = thrown exception object reference
Exception1 e1 = new MyException();
The above statement is a valid Java statement only if the
MyException
class is a subclass of the
Exception1
class, or
MyException
and
Exception1
are the same class. If the above statement is valid, the runtime will assign
the reference of the
MyException
object to
e1
, and then execute the code inside the first
catch
block. If the above
statement is not a valid statement, the runtime will apply the same check for the second
catch
block by using the
following statement:
// Catch parameter declaration = thrown exception object reference
Exception2 e2 = new MyException();
If the above statement is valid, the
MyException
object is assigned to
e2
and the body of the
catch
block is
executed. If the above statement is not valid, the runtime did not find a matching
catch
block for the exception
thrown in the
try
block, and then a different execution path is chosen, which I will discuss shortly.
Typically, you add a
catch
block after a
try
block for every type of exception that can be thrown from the
try
block. Suppose there is a
try
block and it can throw three kinds of exceptions, which are represented by three classes,
Exception1
,
Exception2
, and
Exception3
. Suppose
Exception1
is the superclass of
Exception2
, and
Exception2
is
the superclass of
Exception3
. The class hierarchy for the three exception classes is shown in Figure
9-3
.