fastread homefastrread library fastread menu

Java : Exception propagation

Tutorial by:Arena Buocel      Date: 2016-04-30 01:50:44

❰ Previous Next ❱

An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method,If not caught there, the exception again drops down to the previous method, and so on until they are caught or until they reach the very bottom of the call stack.This is called exception propagation.

Rule: By default Unchecked Exceptions are forwarded in calling chain (propagated).

Program of Exception Propagation

 
  1. class TestExceptionPropagation1{  
  2.   void m(){  
  3.     int data=50/0;  
  4.   }  
  5.   void n(){  
  6.     m();  
  7.   }  
  8.   void p(){  
  9.    try{  
  10.     n();  
  11.    }catch(Exception e){System.out.println("exception handled");}  
  12.   }  
  13.   public static void main(String args[]){  
  14.    TestExceptionPropagation1 obj=new TestExceptionPropagation1();  
  15.    obj.p();  
  16.    System.out.println("normal flow...");  
  17.   }  
  18. }  

 

Output:exception handled

       normal flow...

exception propagation

In the above example exception occurs in m() method where it is not handled,so it is propagated to previous n() method where it is not handled, again it is propagated to p() method where exception is handled.

Exception can be handled in any method in call stack either in main() method,p() method,n() method or m() method.


Rule: By default, Checked Exceptions are not forwarded in calling chain (propagated).

Program which describes that checked exceptions are not propagated

 
  1. class TestExceptionPropagation2{  
  2.   void m(){  
  3.     throw new java.io.IOException("device error");//checked exception  
  4.   }  
  5.   void n(){  
  6.     m();  
  7.   }  
  8.   void p(){  
  9.    try{  
  10.     n();  
  11.    }catch(Exception e){System.out.println("exception handeled");}  
  12.   }  
  13.   public static void main(String args[]){  
  14.    TestExceptionPropagation2 obj=new TestExceptionPropagation2();  
  15.    obj.p();  
  16.    System.out.println("normal flow");  
  17.   }  
  18. }  

 

Output:Compile Time Error

❰ Previous Next ❱


Java

Submit Your Thought, Tutorial, Articls etc.

Submit Your Information India's Number one online promotion website