Java — Determine output with RuntimeException, multiple catch blocks, and finally: public class X { public static void main(String [] args) { try { badMethod(); System.out.print("A"); } catch (RuntimeException ex) /* Line 10 */ { System.out.print("B"); } catch (Exception ex1) { System.out.print("C"); } finally { System.out.print("D"); } System.out.print("E"); } public static void badMethod() { throw new RuntimeException(); } }

Difficulty: Easy

Correct Answer: BDE

Explanation:

Introduction / Context:This problem checks exception selection among multiple catch blocks and confirms that finally always executes, followed by normal execution after the try-catch-finally completes.

Given Data / Assumptions:

  • badMethod throws RuntimeException.
  • There are two catch blocks: first for RuntimeException, then for Exception.
  • A finally block prints "D", and after the try-catch-finally, "E" is printed.

Concept / Approach:Catch selection goes top-down: the first compatible catch handles the exception. RuntimeException matches the first catch, so the second catch is skipped. finally executes regardless, then the flow continues.

Step-by-Step Solution:

badMethod throws RuntimeException.catch (RuntimeException) executes and prints "B".finally executes and prints "D".After try-catch-finally, "E" prints.

Verification / Alternative check:Swap the order of catch blocks (Exception first) to see a compilation error due to unreachable catch for RuntimeException.

Why Other Options Are Wrong:

  • "BD" omits the final "E".
  • "BCD"/"BCDE" incorrectly assume both catches can run.

Common Pitfalls:Expecting the code after throw to run (the "A" is never reached). Misunderstanding that only one matching catch runs.

Final Answer:BDE

More Questions from Exceptions

Discussion & Comments

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