finally block in java

We have learned about try block and catch block in java. In this topic, we will read what is finally block in java and how to finally keyword in java. Let’s discuss the try catch finally java in the example

Here is the table content of the article will we will cover this topic.
1. What is finally block?
2. finally block without catch block?
3. finally block with catch block?
4. Important points of finally block?

5. finally, block with a return statement?
6. finally block with System.exit()?
7. Exception in the finally block?

What is finally block in java?

The “finally block” executes after the execution of the try block. A “finally block” contains all statements that must be executed whether an exception occurs or not. If you want to perform any necessary operation in your program whether an exception occurs or not, then you can use finally block.

There are two ways to use the finally block:

A finally block without any catch block

You can use the finally block with a try block. It’s not mandatory to use a catch block with a try. The catch and finally block are optional but you can’t skip both at the same time. So, if you are using try block then you should use either catch or finally block. You can’t use the finally block without a try block.

try 
{
    // code that might throw an exception
} 
finally 
{
   //Statements to be executed
}

There are two cases:

i. If no exception is raised in the try block, the try block will be executed and control will be transferred to the finally block, then the rest of the code will be executed.
ii. If any exception is raised in the try block, then the rest of the try block doesn’t execute and control will be transferred to the finally block, and the rest of the code will not be executed.

finally block in java

The first case when no exception is raised:

Let’s discuss this scenario with an example. In this example, we are printing some strings. We are using try block with finally block and skipping the use of catch block.

public class ExampleFinallyWithoutCatchBlock
{  
  public static void main(String args[])
  {  
  	try
  	{   
		System.out.println("This code is inside in the try block");  
		String s = "Ravikant";
		System.out.println("result of calculation = "+ s);
  		System.out.println("Rest code inside the try block");
  	}
	finally
	{
		System.out.println("This is finally block"); 
	}
	   //rest code of the program   
  	 System.out.println("This code is outside from the try block");  
  }  
}  

Output: This code is inside in the try block
result of calculation = Ravikant
Rest code inside the try block
This is finally block
This code is outside from the try block

Explanation of example: There is no exception raised in the try block. So, the try block will get executed successfully, and after that finally block and the rest of the code execute.

The second case when an exception is raised:

In this example, we are printing some strings. We are using try block with finally block and skipping the use of catch block.

public class ExampleFinallyWithoutCatchBlock
{  
  public static void main(String args[])
  {  
  	try
  	{   
		System.out.println("This code is inside in the try block");  
		String s = null;
		System.out.println("result of calculation = "+ s.toString()); 
		System.out.println("Rest code inside the try block"); 
  	}
	finally
	{
		System.out.println("This is finally block"); 
	}
	   //rest code of the program   
  	 System.out.println("This code is outside from the try block");  
  }  
} 

Output: This code is inside in the try block
This is finally block
Exception in thread “main” java.lang.NullPointerException at ExampleFinallyWithoutCatchBlock.main(ExampleFinallyWithoutCatchBlock.java:9)

Explanation of example: In the above example exception raised in the try block. After the occurrence of exception try block doesn’t execute and control directly goes to finally block. Rest of the code will not be executed.

2. finally block with a catch block

You can use finally block with try and catch block. You must place the finally block after the catch block. Because you can’t place any statement/block between try and catch block.

try 
{
    // code that might throw an exception
} 
Catch
{
	// Exception handling
}
finally {
   //Statements to be executed
}

There are two cases:

i. If no exception is raised in a try block, the try block executes successfully, and the catch block will be skipped automatically because no one exception occurred in the try block. And control will be transferred to the finally block, then the rest of the code will be executed.
ii. If any exception is raised in the try block, then the rest of the try block doesn’t execute and controls go to the catch block as an exception handled by the catch block. After that control will be transferred to finally block, and the rest of the code will execute.

finally block in java

The first case when no exception is raised:

Let’s discuss this scenario when no exception is raised. In this example, we are printing some strings. We are using finally block with try and catch block.

public class ExampleFinallyWithCatchBlock
{  
  public static void main(String args[])
  {  
  	try
  	{   
		System.out.println("This code is inside in the try block");  
		String s = "Ravikant";
		System.out.println("result of calculation = "+ s);
  		System.out.println("Rest code inside the try block");
  	}
	catch(Exception e)
	{
		e.printStackTrace();
                System.out.println("If any exception raised in try block then catch 
                block will execute");
	}
	finally
	{
		System.out.println("This is finally block"); 
	}
	   //rest code of the program   
  	 System.out.println("This code is outside from the try block");  
  }  
} 

Output: This code is inside in the try block
result of calculation = Ravikant
Rest code inside the try block
This is finally block
This code is outside from the try block

Explanation of example: There is no exception raised in try block. So, try block executes successfully. The catch block will be skipped automatically. After execution of try block control directly jump to finally block and rest of code executes.

Second case when the exception is raised:

In this example, we are printing some strings. We are using finally block with try and catch block.

public class ExampleFinallyWithCatchBlock
{  
  public static void main(String args[])
  {  
  	try
  	{   
		System.out.println("This code is inside in the try block");  
		String s = null;
		System.out.println("result of calculation = "+ s.toString()); 
		System.out.println("Rest code inside the try block"); 
  	}
	catch(Exception e)
	{
		e.printStackTrace();
                System.out.println("If any exception raised in try block then catch 
                block will execute");
	}	
  	finally
	{
		System.out.println("This is finally block"); 
	}
	   //rest code of the program   
  	 System.out.println("This code is outside from the try block");  
  }  
}  

Output: This code is inside in the try block
java.lang.NullPointerException at ExampleFinallyWithCatchBlock.main(ExampleFinallyWithCatchBlock.java:9)
If any exception raised in try block then catch block will execute This is finally block This code is outside from the try block

Explanation of example: In above example exception raised in try block. After the occurrence of exception try block doesn’t execute and control directly goes catch block. catch block handling the exception and print some line of code. After handling the exception now finally block will be execute and then rest of code will be execute.

Important points of finally block

  • The finally block is optional, you can handle any exception by using try and catch block.
  • You can’t use finally block without a try block. You should place the statements in this block that must be executed either exception occurs or not.
  • If any exception occurs in finally block, then you need to handle it.

Use of finally block in java with some important statements

1. finally block with a return statement

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

Let’s try to explain with an example, In this example, we are printing calculated data which is returned by a method calculatedData() and its return type is String. See the Use of finally block in java

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 the try block when the compiler encounters the return statement in the try block it directly jumps to finally block and execute that block. It will override the return statement of the try block.

2. finally block with System.exit()

As you know exit() is a method used to terminate the current Java virtual machine running on the system. If you are using this method in your program, then the compiler will not execute the finally block.

public class UseOfExitMethodWithFinallyBlock
{  
  public static void main(String args[])
  {  
  	try
  	{   
		System.out.println("This code is inside in the try block");  
		System.out.println("Rest code inside the try block"); 
		System.exit(0); 
  	}
	catch(Exception e)
	{
		e.printStackTrace();
                System.out.println("If exception raised, catch block will execute");
	}	
  	finally
	{
		System.out.println("This is finally block"); 
	}
	   //rest code of the program   
  	 System.out.println("This code is outside from the try block");  
  }  
}

Output: This code is inside in the try block
Rest code inside the try block

3. Exception in the finally block

finally block will not be executed if any exception is raised in finally. Because exception behaves the same for all blocks.

public class Exception in ExceptionRaisedInFinallyBlock
{  
  public static void main(String args[])
  {  
  	try
  	{   
		System.out.println("This code is inside in the try block");  
		System.out.println("Rest code inside the try block"); 
		
  	}
	catch(Exception e)
	{
		e.printStackTrace();
System.out.println("If any exception raised in try block then catch block will execute");
	}	
  	finally
	{
		int a = 2/0;
		System.out.println("This is finally block"); 
	}
	   //rest code of the program   
  	 System.out.println("This code is outside from the try block");  
  }  
} 

Output: This code is inside in the try block
Rest code inside the try block
Exception in thread “main” java.lang.ArithmeticException: / by zero       at ExceptionRaisedInFinallyBlock.main(ExceptionRaisedInFinallyBlock.java:18)

3 thoughts on “finally block in java”

  1. I have recently started a site, the info you offer on this site has helped me greatly. Thanks for all of your time & work. “‘Tis our true policy to steer clear of permanent alliances with any portion of the foreign world.” by George Washington.

  2. Generally I do not read article on blogs, but I would like to say that this write-up very forced me to try and do it! Your writing style has been amazed me. Thanks, quite nice article.

  3. I am often to blogging and i really appreciate your content. The article has really peaks my interest. I am going to bookmark your site and keep checking for new information.

Leave a Comment

Follow us on Instagram & watch the latest videos on YouTube. Click below social icons to visit our Instagram & YouTube profiles.