Home / Questions / What is the purpose of the finally clause in a try-catch-finally statement?
Explanatory Question

What is the purpose of the finally clause in a try-catch-finally statement?

👁 33 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

Answer with Explanation

The finally clause ensures that certain code executes whether or not an exception occurs.
It is used to release resources, close files, or perform cleanup operations.

Example:


try {
    FileInputStream file = new FileInputStream("data.txt");
}
catch (IOException e) {
    System.out.println("File error occurred!");
}
finally {
    System.out.println("Closing file and cleaning up resources.");
}