In Java, what will the following program print when no exception is thrown in the try block? public class X { public static void main(String [] args) { try { badMethod(); System.out.print("A"); } catch (Exception ex) { System.out.print("B"); } finally { System.out.print("C"); } System.out.print("D"); } public static void badMethod() {} }
-
AAC
-
BBC
-
CACD
-
DABCD
-
ENone of the above
Answer
Correct Answer: ACD
Explanation
Introduction / Context:This question tests control flow through try/catch/finally when no exception occurs. The finally block always executes, regardless of whether an exception is thrown or caught.
Given Data / Assumptions:
- badMethod() does nothing and throws no exception.
- try prints "A" after calling badMethod().
- catch (Exception) prints "B" only if an Exception is thrown.
- finally always prints "C". After the try-catch-finally, "D" is printed.
Concept / Approach:No exception is thrown, so the catch block is skipped. The finally block executes and then control continues after the try/catch/finally.
Step-by-Step Solution:
Call badMethod() → no exception.Print "A" inside try.Skip catch. Execute finally → prints "C".After the block, print "D".Verification / Alternative check:Add a throw in badMethod() and see how the flow changes (catch would run, but finally still runs).
Why Other Options Are Wrong:"AC" misses the final "D"; "ABCD" would require an exception that is caught (printing "B"), which does not happen.
Common Pitfalls:Thinking finally is conditional; forgetting the last print after the try/catch/finally.
Final Answer:ACD