Java — Output with unchecked exception, single broad catch, finally, and trailing print: public class X { public static void main(String [] args) { try { badMethod(); /* Line 7 */ System.out.print("A"); } catch (Exception ex) /* Line 10 */ { System.out.print("B"); /* Line 12 */ } finally /* Line 14 */ { System.out.print("C"); /* Line 16 */ } System.out.print("D"); /* Line 18 */ } public static void badMethod() { throw new RuntimeException(); } }

Difficulty: Easy

Correct Answer: BCD

Explanation:


Introduction / Context:
This reinforces exception handling flow: code after a throw is skipped, the matching catch runs, finally runs, and then execution continues after try-catch-finally.



Given Data / Assumptions:

  • badMethod throws RuntimeException (unchecked).
  • There is a single catch (Exception) which covers RuntimeException.
  • finally prints "C", and after the block "D" is printed.


Concept / Approach:
Throwing RuntimeException transfers control directly to catch. finally executes regardless, and execution then resumes after the try-catch-finally.



Step-by-Step Solution:

badMethod throws RuntimeException; "A" is not printed.catch (Exception) prints "B".finally prints "C".After the block, "D" prints.


Verification / Alternative check:
Remove the throw to see "A" followed by "C" and then "D".



Why Other Options Are Wrong:
They omit one or more required letters or assume "A" prints, which it does not.



Common Pitfalls:
Forgetting that finally runs even after a handled exception; and believing execution stops after catch (it continues).



Final Answer:
BCD

More Questions from Exceptions

Discussion & Comments

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