In Java, what is the precise output order and behavior for this program using a try/finally with a thrown RuntimeException? public class MyProgram {\n public static void throwit() { throw new RuntimeException(); }\n public static void main(String args[]) {\n try {\n System.out.println("Hello world ");\n throwit();\n System.out.println("Done with try block ");\n } finally {\n System.out.println("Finally executing ");\n }\n }\n}

Difficulty: Easy

Correct Answer: The program will print Hello world, then will print Finally executing, then will print that a RuntimeException has occurred.

Explanation:


Introduction / Context:
This question probes your understanding of try/finally semantics and unchecked exceptions in Java. It matters whether finally executes before, after, or instead of exception propagation and what happens to statements following a throw inside try.


Given Data / Assumptions:

  • throwit() throws a RuntimeException (unchecked).
  • There is no catch block; only finally is present.
  • System.out prints are line-buffered but order is deterministic.


Concept / Approach:
When a throw occurs inside a try and no catch handles it, the JVM still guarantees execution of the finally block before the exception propagates out. Any statements in the try after the throw are skipped. After finally runs, the uncaught exception reaches the runtime, which prints a stack trace (or an error line) after the program's own output.


Step-by-Step Solution:
Prints: "Hello world " from the first println.throwit() is invoked and throws RuntimeException immediately."Done with try block " is never reached.finally executes and prints "Finally executing ".The unhandled RuntimeException then propagates; the JVM prints the exception message/stack trace after finally.


Verification / Alternative check:
Insert a catch before finally and observe the change; or run the code and see the printed order with the stack trace last.


Why Other Options Are Wrong:
Option B places the exception message before finally and claims the skipped try println executes.
Option C omits the mandatory finally execution.
Option A/E are incorrect because the code compiles and certainly produces output.


Common Pitfalls:
Assuming finally executes after program termination or that an exception bypasses finally; both are incorrect.


Final Answer:
The program will print Hello world, then will print Finally executing, then will print that a RuntimeException has occurred.

Discussion & Comments

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