-
The finally block is a block of code that always executes, whether or not an exception occurs.
-
It is mainly used to release resources such as files, database connections, or network sockets.
Syntax:
try {
// Code that may throw exception
}
catch (Exception e) {
// Handle exception
}
finally {
// Code that always executes
}
Example:
import java.io.*;
public class FinallyExample {
public static void main(String args[]) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("MyFile.java"));
System.out.println("Reading file...");
}
catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
finally {
System.out.println("Finally block executed. Closing reader.");
try {
if(reader != null) reader.close();
} catch (IOException e) {
System.out.println("Error closing reader");
}
}
}
}
Output:
Error: MyFile.java (No such file or directory)
Finally block executed. Closing reader.