World's most popular travel blog for travel bloggers.

Java Exception Propagation

, , No Comments

A. Exception Propagation : Unchecked Exception

Before explaining the concept of exception propagation , review the below code with care –
class ExceptionPropagation{
  
  void method3(){
    int result = 100 / 0;  //Exception Gere
  }
  
  void method2(){
    method3();
  }
  
  void method1(){
    try{
 method2();
    } catch(Exception e){
 System.out.println("Exception is handled here");
    }
  }
  
  public static void main(String args[]){
 ExceptionPropagation obj=new ExceptionPropagation();
 obj.method1();
 System.out.println("Continue with Normal Flow...");
  }
}

Output :

Exception is handled here
Continue with Normal Flow...

Explanation : Exception Propagation

When exception is occurred at the top of the stack and no exception handler is provided then exception is propagated –

We can see that
  1. exception is occurred in the method3() and in method3() we don’t have any exception handler.
  2. Uncaught exception will be propagated downward in stack i.e it will check appropriate exception handler in the method2().
  3. Again in method2 we don’t have any exception handler then again exception is propagated downward to method1() where it finds exception handler
Thus we can see that uncaught exception is propagated in the stack until stack becomes empty, this propagation of uncaught exception is called as Exception Propagation.

B. Exception Propagation : Checked Exception

class ExceptionPropagation{
  
  void method3(){
    throw new java.io.IOException("Checked Exception..");
  }
  
  void method2(){
    method3();
  }
  
  void method1(){
    try{
 method2();
 } catch(Exception e){
 System.out.println("Exception is handled here");
 }
  }
  
  public static void main(String args[]){
 ExceptionPropagation obj=new ExceptionPropagation();
 obj.method1();
 System.out.println("Continue with Normal Flow...");
  }
}

Output :

Compile Time Error
You must remember one rule of thumb that – “Checked Exceptions are not propagated in the chain“. thus we will get compile error in the above case –

External More Help :

Refer this guide to know more about important guidelines on Exception propagation

0 comments:

Post a Comment

Let us know your responses and feedback