Java Reference
In-Depth Information
inal exception's information and stack trace are lost . Earlier Java versions provided no
mechanism to wrap the original exception information with the new exception's informa-
tion to provide a complete stack trace showing where the original problem occurred. This
made debugging such problems particularly difficult. Chained exceptions enable an ex-
ception object to maintain the complete stack-trace information from the original excep-
tion. Figure 11.7 demonstrates chained exceptions.
1
// Fig. 11.7: UsingChainedExceptions.java
2
// Chained exceptions.
3
4
public class UsingChainedExceptions
5
{
6
public static void main(String[] args)
7
{
8
try
9
{
10
method1();
11
}
12
catch (Exception exception) // exceptions thrown from method1
13
{
14
exception.printStackTrace();
15
}
16
}
17
18
// call method2; throw exceptions back to main
19
public static void method1()
throws Exception
20
{
21
try
22
{
23
method2();
24
} // end try
25
catch (Exception exception) // exception thrown from method2
26
{
27
throw new Exception( "Exception thrown in method1" , exception);
28
}
29
}
30
31
// call method3; throw exceptions back to method1
32
public static void method2()
throws Exception
33
{
34
try
35
{
36
method3();
37
}
38
catch (Exception exception) // exception thrown from method3
39
{
40
throw new Exception( "Exception thrown in method2" , exception);
41
}
42
}
43
Fig. 11.7 | Chained exceptions. (Part 1 of 2.)
 
Search WWH ::




Custom Search