«Back to Home

Core Java

Topics

Exception Propagation In Java

Exception Propagation
 
An exception is thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method and if not caught there, the exception again drops down to the previous method and so on, until they are caught or they reach the very bottom of the call stack. It is called an exception propagation in Java.
 
In Java, Unchecked Exceptions are forwarded in calling chain (propagated) by default.
 
Let’s see an example, given below.
 
Code
  1. package exceptionHandling;  
  2.   
  3. public class ExceptionPropagation {  
  4.   
  5.     void msg() {  
  6.         int n = 58 / 0;  
  7.     }  
  8.   
  9.     void call() {  
  10.         msg();  
  11.     }  
  12.   
  13.     void phone() {  
  14.         try {  
  15.             call();  
  16.         } catch (Exception e) {  
  17.             System.out.println("Exception.....");  
  18.         }  
  19.     }  
  20.   
  21.     public static void main(String args[]) {  
  22.         ExceptionPropagation obj = new ExceptionPropagation();  
  23.         obj.phone();  
  24.         System.out.println("Rest Code...");  
  25.     }  
  26. }  
22
 
Output

23

24
 
In the example, mentioned above, we can see that exception occurs in m() method and it is not handled. Thus, it is propagated to previous n() method and again it is not handled. Again, it is propagated to p() method and here an exception is handled.
 
Exception can handle in any method in call stack either in main() method, p() method, n() method or m() method.
 
In Java, Checked Exceptions are not forwarded in calling chain (propagated) by default.
 
Let’s see an example, given below of checked exceptions is not propagated.
 
Code
  1. package exceptionHandling;  
  2.   
  3. public class ExceptionPropagation {  
  4.   
  5.     void msg() {  
  6.         throw new java.io.IOException("device error"); //compile time error  
  7.     }  
  8.   
  9.     void call() {  
  10.         msg();  
  11.     }  
  12.   
  13.     void phone() {  
  14.         try {  
  15.             call();  
  16.         } catch (Exception e) {  
  17.             System.out.println("Exception.....");  
  18.         }  
  19.     }  
  20.   
  21.     public static void main(String args[]) {  
  22.         ExceptionPropagation obj = new ExceptionPropagation();  
  23.         obj.phone();  
  24.         System.out.println("Rest Code...");  
  25.     }  
  26. }  
25

Summary

Thus, we learnt that Unchecked Exceptions are forwarded in calling chain (propagated) and Checked Exceptions are not forwarded in calling chain (propagated) by default and also learnt how we can create it in Java.