In Java, what is the output of this program when a RuntimeException is thrown and handled, with a finally block executing? public class RTExcept { public static void throwit() { System.out.print("throwit "); throw new RuntimeException(); } public static void main(String [] args) { try { System.out.print("hello "); throwit(); } catch (Exception re) { System.out.print("caught "); } finally { System.out.print("finally "); } System.out.println("after "); } }
-
Ahello throwit caught
-
BCompilation fails
-
Chello throwit RuntimeException caught after
-
Dhello throwit caught finally after
-
ENone of the above
Answer
Correct Answer: hello throwit caught finally after
Explanation
Introduction / Context:This program demonstrates thrown unchecked exceptions (RuntimeException), catching with a broad Exception handler, and guaranteed execution of finally, followed by code after the try/catch/finally.
Given Data / Assumptions:
- throwit() prints "throwit " then throws new RuntimeException().
- try prints "hello " then calls throwit().
- catch (Exception) handles the RuntimeException and prints "caught ".
- finally prints "finally ".
- After the block, println prints "after " with a newline.
Concept / Approach:Unchecked exceptions (RuntimeException) do not require a throws clause. Once thrown, control transfers to the nearest matching catch, then finally runs, then execution continues after the try/catch/finally.
Step-by-Step Solution:
Output sequence: "hello " (from try) → "throwit " (from throwit) → exception thrown.Catch executes: prints "caught ".Finally executes: prints "finally ".After block: prints "after " and newline.Verification / Alternative check:Change catch to catch(RuntimeException) and behavior remains the same; removing catch would still run finally and then terminate with an exception.
Why Other Options Are Wrong:They either omit finally/after or imply compilation errors that do not occur for unchecked exceptions.
Common Pitfalls:Thinking unchecked exceptions must be declared; forgetting that finally runs even when an exception is thrown and caught.
Final Answer:hello throwit caught finally after