Home / Questions / What is a finally block? When and how is it used? Give an example.
Explanatory Question

What is a finally block? When and how is it used? Give an example.

👁 45 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 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.