✅ 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:
- Final Variable: Value cannot be changed after assignment
- Final Method: Cannot be overridden by subclasses
- Final Class: Cannot be subclassed
🧠 Key Differences: finally
vs final
Feature | finally | final |
---|---|---|
Category | Exception handling keyword | Non-access modifier |
Primary Use | Ensures execution of cleanup code | Prevents changes (immutability, inheritance, overriding) |
Context | Used with try-catch blocks | Used with variables, methods, or classes |
Execution | Always executes (except for System.exit ) | Not a block, but a modifier |
Related To | Resource management | Code 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.