finally, block with a return statement

As we know finally block, always execute whether an exception occurs or not. If you are using return statement in, try or catch block then finally block override the return of try/catch block. It means when compiler encounters the return statement in try/catch block it directly jumps to finally block and execute the statements of finally block.

Let’s try to explain with an example, In this example, we are printing calculated data which is return by a method calculatedData() and its return type is String.

public class UseOfReturnWithFinallyBlock
{  
  public static void main(String args[])
  {  
  	  System.out.println(calculatedData());
  }  
  public static String calculatedData()
  {
	  String calculatedData = null;
	try
	{
		calculatedData = "This data is return from try block";
		return calculatedData;
	}
	catch(ArithmeticException e)
	{
		e.printStackTrace();
		calculatedData = "This data is return from catch block";
		return calculatedData;
	}
	finally
	{
		calculatedData = "This data is return from finally block";
		return calculatedData;
	}
  }
}

Output: This data is return from finally block

Explanation: There is no exception raised in a try block, so it is executed successfully. During the execution of try block when compiler encounters the return statement in try block it directly jumps to finally block and execute that block. It will override the return statement of the try block.

Leave a Comment