In Java, what will be printed when a try block runs normally and a finally block executes afterward? public class MyProgram { public static void main(String args[]) { try { System.out.print("Hello world "); } finally { System.out.println("Finally executing "); } } }

Difficulty: Easy

Correct Answer: Hello world Finally executing

Explanation:

Introduction / Context:Java allows a try block with a finally block even without any catch clauses. The finally block guarantees cleanup or final actions after the try completes, whether or not an exception occurs.

Given Data / Assumptions:

  • try prints "Hello world " but throws no exception.
  • finally prints "Finally executing " with println (newline at the end).
  • No catch block is present; this is valid Java.

Concept / Approach:When no exception is thrown, control flows from try to finally, then exits the method. Both outputs are printed in sequence.

Step-by-Step Solution:

Execute try: prints "Hello world ".Execute finally: prints "Finally executing " (followed by a newline).Program ends; combined output reads as "Hello world Finally executing".

Verification / Alternative check:Add an exception inside try: the finally will still run before the program terminates or a catch (if present) runs.

Why Other Options Are Wrong:Options claiming compilation failure are incorrect; Java permits try-finally without catch. Output is not only "Hello world." because finally adds more text.

Common Pitfalls:Assuming a catch is mandatory with try; it is not if finally is present.

Final Answer:Hello world Finally executing

More Questions from Exceptions

Discussion & Comments

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