finally Block
The finally block in Java is used to execute important cleanup code regardless of whether an exception occurs or not. It ensures that critical resources are released, making programs safe and reliable.
This is a high-frequency interview topic, often asked with tricky edge cases.
What Is the finally Block?
- Always executes after try and catch
- Used for cleanup operations
- Executes whether exception occurs or not
- Ensures program stability
Basic Syntax
try {
// risky code
} catch (Exception e) {
// handling code
} finally {
// cleanup code
}
Why finally Is Important
- Closes resources (files, DB, network)
- Releases memory
- Restores system state
- Avoids resource leaks
- Ensures predictable execution
Basic Example
try {
int a = 10 / 2;
} catch (ArithmeticException e) {
System.out.println("Error");
} finally {
System.out.println("Finally block executed");
}
Output:
Finally block executed
Result: ✔ Executes even when no exception occurs
Execution Scenarios (Very Important)
1️⃣ No Exception Occurs
try {
int x = 10 / 2;
} catch (Exception e) {
} finally {
System.out.println("Finally");
}
✔ finally executes
2️⃣ Exception Occurs and Is Caught
try {
int x = 10 / 0;
} catch (ArithmeticException e) {
} finally {
System.out.println("Finally");
}
✔ finally executes
3️⃣ Exception Occurs and Is NOT Caught
try {
int x = 10 / 0;
} finally {
System.out.println("Finally");
}
✔ finally executes
❌ Program terminates after finally
Can finally Exist Without catch?
✔ Yes
try {
int x = 10 / 2;
} finally {
System.out.println("Cleanup");
}
❌ catch is optional
✔ finally is optional
When finally Does NOT Execute (Rare but Important)
1. System.exit() is Called
try {
System.exit(0);
} finally {
System.out.println("Finally");
}
❌ finally will NOT execute
2. JVM Crash / Power Failure
- JVM shuts down unexpectedly
- finally cannot run
return Statement and finally
Example
int test() {
try {
return 10;
} finally {
System.out.println("Finally");
}
}
✔ Output:
Finally
✔ Method returns 10 after finally
return in finally (Very Dangerous)
int test() {
try {
return 10;
} finally {
return 20;
}
}
❌ Output:
20
- ⚠️ finally overrides return value
- ⚠️ Strongly discouraged
finally vs try-with-resources
Traditional Cleanup
FileReader fr = null;
try {
fr = new FileReader("file.txt");
} finally {
if (fr != null) fr.close();
}
Modern Approach (Java 7+)
try (FileReader fr = new FileReader("file.txt")) {
// use file
}
- ✔ Automatic resource cleanup
- ✔ Cleaner and safer
Common Beginner Mistakes
- Writing business logic in finally
- Using return inside finally
- Forgetting that finally always executes
- Not handling resource cleanup properly
- Assuming finally always executes (ignoring System.exit)
Interview-Ready Answers
Short Answer
The finally block is used to execute cleanup code whether an exception occurs or not.
Detailed Answer
In Java, the finally block is executed after try and catch blocks regardless of whether an exception is thrown or handled. It is typically used for resource cleanup such as closing files or database connections. The only cases where finally does not execute are JVM termination or system exit.
Key Takeaway
finally guarantees cleanup. Use it for resource release, not for business logic. Avoid return inside finally to prevent unexpected behavior.