Java finally block
Created By: chatGPT
Java's
finally
block is used as a mechanism to ensure that a section of code always executes irrespective of whether an exception occurred or not. It is commonly used to perform clean-up activities, like closing file streams or releasing resources. The finally
block follows a try
block and may be associated with an optional catch
block.try {
// Code that may throw an exception
int result = 10 / 0;
} catch (ArithmeticException e) {
// Handle the exception
System.out.println("Caught an ArithmeticException: " + e.getMessage());
} finally {
// This block always executes
System.out.println("Finally block executed.");
}
In the example above, the code in the
try
block attempts to execute a division that results in an ArithmeticException due to division by zero. The catch
block handles the exception, printing an error message. Regardless of the exception, the message from the finally
block will always be shown, confirming that its statements are executed last.try {
// Code that may throw an exception
FileInputStream file = new FileInputStream("file.txt");
} catch (FileNotFoundException e) {
// Handle the exception
System.out.println("File not found: " + e.getMessage());
} finally {
// Clean up resources
// Assuming 'file' is a resource we may need to close
if (file != null) {
try {
file.close();
} catch (IOException e) {
System.out.println("Error closing the file: " + e.getMessage());
}
}
System.out.println("Finally block executed. Resources cleaned up.");
}