Exception Propagation In Java

When an exception is initially raised, it starts from the top of the stack. If unhandled, it propagates down the call stack to the preceding method. If still uncaught, the exception continues descending through each preceding method until either it is handled or it reaches the bottom of the call stack. This process is known as exception propagation.

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

Exception Propagation Example

TestExceptionPropagation1.java

Example

class TestExceptionPropagation1{

  void m(){

    int data=50/0;

  }

  void n(){

    m();

  }

  void p(){

   try{

    n();

   }catch(Exception e){System.out.println("exception handled");}

  }

  public static void main(String args[]){

   TestExceptionPropagation1 obj=new TestExceptionPropagation1();

   obj.p();

   System.out.println("normal flow...");

  }

}

Output:

Output

exception handled

       normal flow...

In the given scenario, an exception arises within the m function without being caught, leading to its propagation to the preceding n function where it is also unhandled, and subsequently to the p function where the exception is properly handled.

An exception can be managed at any level of the call stack, whether it is within the main function, p function, n function, or m function.

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

Exception Propagation Example

TestExceptionPropagation1.java

Example

class TestExceptionPropagation2{

  void m(){

    throw new java.io.IOException("device error");//checked exception

  }

  void n(){

    m();

  }

  void p(){

   try{

    n();

   }catch(Exception e){System.out.println("exception handeled");}

  }

  public static void main(String args[]){

   TestExceptionPropagation2 obj=new TestExceptionPropagation2();

   obj.p();

   System.out.println("normal flow");

  }

}

Output:

Output

Compile Time Error

Input Required

This code uses input(). Please provide values below: