What is finally block?
Syntax
try {
// Code that may cause an exception
} catch (ExceptionType e) {
// Code to handle the exception
} finally {
// Code that will be executed regardless of whether an exception occurs or not
}
Example
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
class FileReadExample {
public static void main(String[] args) {
// Specify the file path
String filePath = "example.txt";
BufferedReader reader = null;
try {
// Open a file for reading
reader = new BufferedReader(new FileReader(filePath));
// Read data from the file (this could potentially throw an IOException)
String line = reader.readLine();
System.out.println("Read from file: " + line);
} catch (IOException e) {
// Handle IOException (e.g., log the exception or take appropriate action)
System.err.println("IOException: " + e.getMessage());
} finally {
try {
// Close the file in the finally block to ensure it is always closed
if (reader != null) {
reader.close();
System.out.println("File closed successfully.");
}
} catch (IOException e) {
// Handle IOException during the closing of the file
System.err.println("Error closing file: " + e.getMessage());
}
}
}
}
Note: