In Java, what will the following program print when a return occurs inside try and a finally block is present? public class Foo { public static void main(String[] args) { try { return; } finally { System.out.println("Finally"); } } }

Java Programming Exceptions Difficulty: Easy
Choose an option
  • A
    Finally
  • B
    Compilation fails.
  • C
    The code runs with no output.
  • D
    An exception is thrown at runtime.
  • E
    None of the above

Answer

Correct Answer: Finally

Explanation

Introduction / Context:This question focuses on the guarantee that finally executes even if the try block returns, breaks, or continues. The JVM ensures the finally block runs before control leaves the method.

Given Data / Assumptions:

  • try contains only return.
  • finally prints "Finally".
  • No exceptions are involved.

Concept / Approach:Java specifies that the finally block executes after the try (and any matching catch) but before the method actually returns control to the caller. Therefore, the println in finally will run and produce output.

Step-by-Step Solution:

Enter try → encounter return.Before returning, run finally → prints "Finally".Method then completes with return; no further output.

Verification / Alternative check:Place code after the try/catch/finally; it will be unreachable because of the return, but the finally still runs first.

Why Other Options Are Wrong:Compilation is valid; there is definite output; no exception is thrown.

Common Pitfalls:Believing that return suppresses finally; in Java it does not.

Final Answer:Finally

Discussion & Comments
No comments yet. Be the first to comment!
Join Discussion