The finally block plays an automatic role in exception handling in Java language. That way, a piece of code will execute no matter what happens when the try-or-catch blocks run. The most common thing you will use this for is to release resources like file handles, database connections, or sockets. In this article, We will explain a finally block in Java.
Introduction to finally Block in Java
The finally block in Java is part of the exception handling mechanism that ensures certain code will always run, regardless of whether an exception occurs in the try-and-catch block or not. This block is used to execute import source code, such as closing resources, cleaning up memory, or performing other tasks that need to be done after executing the try-or-catch blocks.
Program
class Main{
public static void main(String args[]){
try{
int data = 10/0 ;
System.out.println(data);
}catch(ArithmeticException e){
System.out.println("Exception Caught"+e);
} finally {
System.out.println("This code will always execute");
}
}
}
Output
Exception Caughtjava.lang.ArithmeticException: / by zero
This code will always execute
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
Syntax of finally block
The finally block follows a try block or a try-catch block, and it looks like this.
try {
// Code that may throw an exception
} catch (Exception e) {
// Handling exception
} finally {
// Code that will always execute
}
Why Use finally in Java?
Finally, a block in Java is usually used to ensure that some specific piece of source code is executed whenever the Java codes are supposed to be from the preceding try block, which always executes, even if an exception occurs. This is very useful for tasks where you need to handle resource cleanup and perform some cleanup; otherwise, you will have resource leaks, and the program will not be stable. An exception occurs within the preceding try block. This is especially useful for tasks such as life resource cleanup, which must be completed to avoid resource leaks and maintain program stability.
Reasons to use finally in Java
Reasons Management: Once you’ve finished with resources such as file streams, sockets, or database connections, you must release them. The final block ensures these resources are closed properly, even if an exception occurs during processing.
Guaranteed Code Execution: The finally block always executes after the try block, whether an exception is thrown or not. This guarantees that the cleanup code is executed and ensures consistent behavior.
Error Handling and Cleanup: We can also use the finally block to perform cleanup actions, such as releasing memory or resetting variable states, regardless of whether the program can handle the exception.
import java.io.File ;
import java.io.FileNotFoundException;
import java.util.Scanner;
class Main{
public static void main(String args[]){
Scanner scanner = null ;
try{
File file = new File("wrodig.txt") ;
scanner = new Scanner(file) ;
while(scanner.hasNextLine()){
String line = scanner.nextLine();
System.out.println(line);
}
}catch(FileNotFoundException e){
System.out.println("File is not found"+e.getMessage());
}finally{
if (scanner != null){
scanner.close();
System.out.println("Scanner closed successfully");
}
}
}
}
Output
File is not foundwrodig.txt (The system cannot find the file specified)
Usage of finally block
Let’s see the different usage examples of finally block in java.
Case 1: When an exception does not occur
Java program does not throw any exception, and the finally block is executed after the try block.
Program
class Main{
public static void main(String args[]){
try{
int divide = 25/ 2 ;
System.out.println(divide);
}catch(NullPointerException e){
System.out.println(e.getMessage()) ;
}finally{
System.out.println("This block always execute");
}
}
}
Output
12
This block always execute
Case 2: When an exception occurs but is not handled by the catch block
In the following example, Code throws an exception. However, the catch block cannot handle it. This final block is executed after the try block, and the program terminates abnormally.
Program
class Main{
public static void main(String args[]){
try{
int divide = 2 /0 ;
System.out.println(divide);
}catch(NullPointerException e){
System.out.println(e.getMessage());
}finally{
System.out.println("finally block is always executed");
}
}
}
Output
finally block is always executed
Exception in thread "main" java.lang.ArithmeticException: / by zero
Case 3: When an exception occurs, it is handled by the catch block
In this scenario, the program throws an exception, but handled by the catch block executes after the catch block.
The finally block is executed after the try block, regardless of whether an exception is thrown. If there is a catch block, it finally runs after it.
Let’s see how it finally works.
If there is not exception occurs in the try block, the finally block runs after the try.
If an exception occurs and is caught by the catch block, the finally block runs after the catch.
If an exception occurs and is not caught, the finally block will still execute before the program terminates.
Conclusion
In this article, we learn about the last block in Java. Resource and cleanup management and completion of tasks up to the exception are crucial. It is used to try and catch blocks to ensure that if something goes wrong, your important source code, like closing files and releasing resources, doesn’t get shot down the toilet. Finally, the block always runs after the try block, except for forced termination. Finally, it makes your source code more robust and reliable by ensuring that cleanup tasks are always done.
FAQs
What is the purpose of the finally block in Java?
The finally block executes code after a try block, regardless of whether an exception is thrown. It is typically used for resource cleanup, such as closing files or cleaning the locks.
Will the finally block always execute?
Yes, the finally block will almost always execute, even if an exception is thrown in the try block. However, rare exceptions exist, such as when System.exit() is called or the JVM (Java Virtual Machine) crashes.
Can a finally block exist without a catch block?
Yes, a finally block can be used with just a try block, without any catch block. The syntax try-finally is common for executing code that must always run, like resource cleanup.
What happens if there is a return statement in the try block?
If the try block contains a return statement, the finally block will still execute before the method actually returns.
Can I have multiple finally blocks?
No, you cannot have multiple finally blocks. A try block can be followed by only one finally block.
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.