Return Statements in finally Blocks
You'll learn why placing return statements in finally blocks creates confusing and dangerous control flow.
The Surprising Behavior
When you put a return statement inside a finally block, it overrides any return statement from the try or catch blocks. This happens because the finally block always executes last, and its return becomes the final word—literally erasing whatever the method was about to return.
public int confusingMethod() {
try {
return 10;
} finally {
return 99; // This wins!
}
// Method returns 99, not 10
}
Even if the try block successfully completes and tries to return 10, the finally block's return 99 takes over. The original return value vanishes.
Even Worse: Swallowing Exceptions
The most dangerous scenario occurs when an exception is thrown:
public int dangerousMethod() {
try {
throw new RuntimeException("Error!");
} finally {
return 42; // Exception disappears!
}
// Method returns 42; exception is never seen
}
The exception gets completely suppressed. No stack trace, no error signal—just a normal return. This makes debugging nearly impossible.
The Rule: Never Do This
Think of finally as a cleanup crew that tidies up after the main action. You wouldn't ask the janitor to rewrite the ending of a play—they're there to turn off the lights, not change the story.
Use finally for cleanup (closing resources, resetting state), never for returning values or altering the method's outcome.
Key Takeaway:
Never use return statements in finally blocks—they override previous returns and can silently suppress exceptions, creating confusing and dangerous bugs.