Bird
0
0

Consider this method:

hard📝 Application Q15 of 15
Java - Exception Handling

Consider this method:

public static int test() {
    try {
        System.out.print("Try-");
        throw new RuntimeException();
    } catch(RuntimeException e) {
        System.out.print("Catch-");
        return 1;
    } finally {
        System.out.print("Finally-");
        return 2;
    }
}

What will System.out.print(test()); output?

ATry-Catch-Finally-1
BTry-Catch-Finally-2
CTry-Finally-2
DCatch-Finally-1
Step-by-Step Solution
Solution:
  1. Step 1: Trace try block execution

    Try prints "Try-" then throws RuntimeException.
  2. Step 2: Catch block handles exception

    Catch prints "Catch-" and returns 1, but return is not final yet.
  3. Step 3: finally block overrides return

    Finally prints "Finally-" and returns 2, overriding previous return 1.
  4. Step 4: Combine printed output and return value

    Printed output is "Try-Catch-Finally-" and method returns 2, so print(test()) outputs "2" after prints.
  5. Final Answer:

    Try-Catch-Finally-2 -> Option B
  6. Quick Check:

    finally return overrides catch return = A [OK]
Quick Trick: finally return overrides other returns [OK]
Common Mistakes:
  • Ignoring finally return overriding catch return
  • Assuming catch return is final
  • Missing printed output before return

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes