Java Reference
In-Depth Information
12.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 12.9 illustrates how to create and throw
chained exceptions.
chained exception
L
ISTING
12.9
ChainedExceptionDemo.java
1
public class
ChainedExceptionDemo {
2
public static void
main(String[] args) {
3
try
{
4 method1();
5 }
6
catch
(Exception ex) {
7
ex.printStackTrace();
stack trace
8 }
9 }
10
11
public static void
method1()
throws
Exception {
12
try
{
13 method2();
14 }
15
catch
(Exception ex) {
16
throw new
Exception(
"New info from method1"
, ex);
chained exception
17 }
18 }
Search WWH ::
Custom Search