Java exception propagation

In java exception propagation is a process in which a exception is being dropped from to the top to the bottom of the stack in the calling chain. It means an exception is first thrown from the top of the stack and if not handled then it drops down to the calling method and again if not handled there then it again falls to the calling method and so on. The process is known as Exception propagation.

Note: Unchecked exceptions are forwarded into the calling chain by default.

Let us discuss exception propagation through the given program.

class PropagationDemo
   {  
  void a()
    {  
    int data=50/0;  
    }  
  void b()
   {  
     a();  
   }  
  void c()
    {  
   try
     {  
     b();  
      }catch(Exception e)
       {
       System.out.println("Interrupt handled");
        }  
    }  
  public static void main(String args[])
   {  
   PropagationDemo obj=new PropagationDemo();  
   obj.c();  
   System.out.println("Rest of the code...");  
  }  
} 

Output:

Explanation of the above program

In the above example unchecked exception (ArithmeticException) occurs in method a ( ) but not handled in a(), then it drops down to calling method b( ) where it is not handled again, then it again drops down to the calling method c ( ) where it is handled using try and catch block.

Thus, exception can be handle in any method in the call stack i.e at method a ( ) or at method b ( ) or method c ( ) or in main ( ) because unchecked exception are propagated by default to its calling chain.

Checked exceptions like IOException and SQLException are not propagated by default to the calling chain in the stack call

Let us discuss this scenario with the help of a java program with respect to the above program.

class PropagationDemo
   {  
  void a()
    {  
    throw new java.io.IOException("File Error"); // Checked Exception
    }  
  void b()
   {  
     a();  
   }  
  void c()
    {  
   try
     {  
     b();  
      }catch(Exception e)
       {
       System.out.println("Interrupt handled");
        }  
    }  
  public static void main(String args[])
   {  
   PropagationDemo obj=new PropagationDemo();  
   obj.c();  
   System.out.println("Rest of the code...");  
  }  
} 

Output:

Explanation:

In the above program we have clearly seen that checked exception i.e. java.io.IOException is not propagated to the calling chain in the call stack by default. Thus, it gives an error message “unreported exception java.io.IOException; must be caught or declared to be thrown”

To overcome this problem we use throws keyword so that checked exception can be propagated in the calling chain in the stack call which we will discuss in the next topic.