March 11, 2024

Exception Propagation in Java

In the execution of the method code, if an exception condition occurs, normal flow of the method is disrupted. In order to handle the exceptional condition an exception object is created and thrown. That exception may be handled in the method where that exception is thrown or it may be passed on to be handled by other methods in the caller stack. This process of going through the method call stack to look for an exception handler that can handle the thrown exception is known as exception propagation in Java.

Exception propagation in Java

To reach to a certain method in the code, some other methods are called in between. This list of methods is known as the method call stack.

When an exception occurs in the current method, exception handling mechanism will look for an exception handler in the current method, if not found it will go to the previous method (caller method of the current method) in the call stack and so on looking for the exception handler that can handle the thrown exception.

If no exception handler is provided for the thrown exception, default exception handler will be called to handle that exception.

Exception Propagation flow

Suppose you have a call stack of three methods method1, method2 and method3. From method1 you call method2 and method3 is called from method2.

If an exception occurs in method 3 and the exception handler is in method1 then the exception propagation in Java can be shown as follows-

exception propagation in java

Exception Propagation in Java with checked and unchecked exceptions

In case of unchecked exception it is not enforced to handle the exception using try-catch block or throws clause so exception propagation happens by default.

In case of checked exception you will have to declare the exception that are not handled with in a method by using throws keyword. That is an indication that exception has to be propagated to the caller method. If caller method wishes to propagate it further then it can also declare the thrown exceptions using the throws keyword.

Exception propagation Java example with unchecked exception

Let’s take the same method hierarchy of three methods as depicted above. Where exception occurs in method3 and propagates to method1 in search of an appropriate exception handler.

public class ExceptionPropagationDemo {
  public static void main(String[] args) {
    ExceptionPropagationDemo ep = new ExceptionPropagationDemo();
    ep.method1();
  }
  // This method forwards the exception
  void method3(){
    System.out.println("In method3");
    int[] numArr = {4,5,6};
    int number = numArr[5];
  }

  // This method forwards the exception
  void method2(){
    System.out.println("In method2");
    method3();
  }
	
  // Exception is handled in this method
  void method1(){
    try{
      System.out.println("In method1");
      method2();
    } catch(Exception e){
      System.out.println("Exception handled");
      e.printStackTrace();
    }
  }
}
Output
In method1
In method2
In method3
Exception handled
java.lang.ArrayIndexOutOfBoundsException: 5
	at com.knpcode.ExceptionPropagationDemo.method3(ExceptionPropagationDemo.java:14)
	at com.knpcode.ExceptionPropagationDemo.method2(ExceptionPropagationDemo.java:20)
	at com.knpcode.ExceptionPropagationDemo.method1(ExceptionPropagationDemo.java:27)
	at com.knpcode.ExceptionPropagationDemo.main(ExceptionPropagationDemo.java:7)

In the above code exception occurs in method3 as there is an attempt to get the value at the index 5 of an array whose length is 3. This will result in ArrayIndexOutOfBoundsException being thrown. Since method3 does not provide any exception handling mechanism so next method (method 2) is searched, there also no exception handling mechanism is found so exception propagates to method1 where it is handled. You can see the same flow in the exception trace where exception originates in method3 and propagates to method1.

Exception propagation Java example with checked exception

In case of checked exception you need to explicitly specify the exceptions using throws clause if you are not providing exception handling with in the method.

Let’s see an example of exception propagation with checked exceptions. Here in method 3 there is a code to read a file and stream is also closed both of these activities may result in checked exception. Since you are forced to handle that exception so you specify it using throws clause. Notice that method2 is not providing exception handling so there also it is specified using throws clause. That way exception propagates to method1 where it is handled.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class ExceptionPropagationDemo {
  public static void main(String[] args) {
    ExceptionPropagationDemo ep = new ExceptionPropagationDemo();
    ep.method1();
  }
  // This method forwards the exception
  void method3() throws IOException{
    System.out.println("In method3");
    BufferedReader br = null;
    try{
      br = new BufferedReader(new
          InputStreamReader(new FileInputStream(new 
              File("D:\\test1.txt"))));
    }finally{
      if(br != null)
        br.close();
    }		
  }
	
  // This method forwards the exception
  void method2() throws IOException{
    System.out.println("In method2");
    method3();
  }
	
  // Exception is handled in this method
  void method1(){
    try{
      System.out.println("In method1");
      method2();
    } catch(IOException e){
      System.out.println("Exception handled");
      e.printStackTrace();
    }
  }
}
Output
In method1
In method2
In method3
Exception handled
java.io.FileNotFoundException: D:\test1.txt (The system cannot find the file specified)
	at java.io.FileInputStream.open0(Native Method)
	at java.io.FileInputStream.open(Unknown Source)
	at java.io.FileInputStream.(Unknown Source)
	at com.knpcode.ExceptionPropagationDemo.method3(ExceptionPropagationDemo.java:22)
	at com.knpcode.ExceptionPropagationDemo.method2(ExceptionPropagationDemo.java:34)
	at com.knpcode.ExceptionPropagationDemo.method1(ExceptionPropagationDemo.java:41)
	at com.knpcode.ExceptionPropagationDemo.main(ExceptionPropagationDemo.java:13)

That's all for the topic Exception Propagation in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment