17.8. (Optional) Chained Exceptions |
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 17.7 gives an example that demonstrates how to create and throw chained exceptions.
1 public class ChainedExceptionDemo { 2 public static void main(String[] args) { 3 try { 4 method1(); 5 } 6 catch (Exception ex) { 7 ex.printStackTrace(); 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); 17 } 18 } 19 20 public static void method2() throws Exception { 21 throw new Exception( "New info from method2" ); 22 } 23 } |
The main method invokes method1 (line 4), method1 invokes method2 (line 13), and method2 throws an exception (line 21). This exception is caught in the catch block in method1 and is wrapped in a new exception in line 16. The new exception is thrown and caught in the catch block in the main method in line 6. Figure 17.9 shows the output from the printStackTrace() method in line 7. The new exception thrown from method1 is displayed first, followed by the original exception thrown from method2 .