Java Reference
In-Depth Information
perform operations before exits;
throw
ex;
}
The statement
throw ex
rethrows the exception to the caller so that other handlers in the
caller get a chance to process the exception
ex
.
14.23
✓
✓
Suppose that
statement2
causes an exception in the following statement:
Check
Point
try
{
statement1;
statement2;
statement3;
}
catch
(Exception1 ex1) {
}
catch
(Exception2 ex2) {
throw
ex2;
}
finally
{
statement4;
}
statement5;
Answer the following questions:
If no exception occurs, will
statement4
be executed, and will
statement5
be
executed?
■
If the exception is of type
Exception1
, will
statement4
be executed, and will
statement5
be executed?
■
If the exception is of type
Exception2
, will
statement4
be executed, and will
statement5
be executed?
■
If the exception is not
Exception1
nor
Exception2
, will
statement4
be exe-
cuted, and will
statement5
be executed?
■
Throwing an exception along with another exception forms a
chained exception
.
Key
Point
In the preceding section, the
catch
block rethrows the original exception. Sometimes, you
may need to throw a new exception (with additional information) along with the original
exception. This is called
chained exceptions
. Listing 14.9 illustrates how to create and throw
chained exceptions.
chained exception
L
ISTING
14.9
ChainedExceptionDemo.java
1
public class
ChainedExceptionDemo {
2
public static void
main(String[] args) {
3
try
{
4 method1();
5 }
6
catch
(Exception ex) {
7
8 }
9 }
10
ex.printStackTrace();
stack trace