Why do we use finally and how it differs from the final keyword?

finally Keyword: Purpose & Usage

The finally block in Java is used with exception handling (try-catch) to define a block of code that always executes, regardless of whether an exception is thrown or caught.

💡 Purpose:

  • Ensures that cleanup code (like closing resources, files, database connections) always runs—even if an exception occurs.

🔧 Syntax:

try {
    // Code that may throw exception
} catch (ExceptionType e) {
    // Exception handling
} finally {
    // Cleanup code that always executes
}

📌 Example:

FileInputStream file = null;
try {
    file = new FileInputStream("data.txt");
    // Read from file
} catch (IOException e) {
    System.out.println("File error!");
} finally {
    if (file != null) {
        file.close(); // Always executed, even if exception is thrown
    }
}

final Keyword: Purpose & Usage

The final keyword is a non-access modifier used to declare constants, prevent method overriding, or prevent class inheritance.

🔍 Use Cases:

  1. Final Variable: Value cannot be changed after assignment
  2. Final Method: Cannot be overridden by subclasses
  3. Final Class: Cannot be subclassed

🧠 Key Differences: finally vs final

Featurefinallyfinal
CategoryException handling keywordNon-access modifier
Primary UseEnsures execution of cleanup codePrevents changes (immutability, inheritance, overriding)
ContextUsed with try-catch blocksUsed with variables, methods, or classes
ExecutionAlways executes (except for System.exit)Not a block, but a modifier
Related ToResource managementCode safety, object immutability

🧠 Bonus: Common Interview Question & Answer

Q: Can a finally block override a return statement in a try block?

A: Yes, the finally block is always executed after the try, even if the try block has a return. However, if the finally also has a return, it overrides the try‘s return.

public int test() {
    try {
        return 1;
    } finally {
        return 2;  // This will be returned
    }
}

🟰 Output: 2

🏁 Final Takeaways

  • finally is about ensuring execution in exception handling.
  • final is about preventing modification, ensuring immutability or inheritance rules.
  • Though they sound similar, they are used in completely different contexts.
  • Knowing where and when to use each is critical for writing robust, secure, and clean Java code.

Leave a Reply

Your email address will not be published. Required fields are marked *