Java — Predict the console output for try/finally with a thrown exception: public class Test { public static void aMethod() throws Exception { try /* Line 5 */ { throw new Exception(); /* Line 7 */ } finally /* Line 9 */ { System.out.print("finally "); /* Line 11 */ } } public static void main(String args[]) { try { aMethod(); } catch (Exception e) /* Line 20 */ { System.out.print("exception "); } System.out.print("finished"); /* Line 24 */ } }

Difficulty: Easy

Correct Answer: finally exception finished

Explanation:


Introduction / Context:
This Java question tests understanding of exception flow with try, finally, and catch in different call frames. It highlights that the finally block always executes, even when an exception is thrown and later caught in the caller.



Given Data / Assumptions:

  • aMethod throws a new Exception inside its try block.
  • aMethod also has a finally block that prints "finally ".
  • main calls aMethod inside a try and catches Exception, printing "exception " and then "finished".


Concept / Approach:
In Java, a finally block runs after try (and optional catch) completes, regardless of whether an exception is thrown. If an exception is not handled in the current method, it propagates outward, but the current method's finally still executes first.



Step-by-Step Solution:

Inside aMethod: throw new Exception() happens.Before leaving aMethod, finally runs and prints "finally ".Exception propagates to main and is caught by catch (Exception e), printing "exception ".After the try-catch in main, "finished" is printed.


Verification / Alternative check:
Comment out the catch in main to see the difference: you would still see "finally " before the program terminates with an uncaught exception.



Why Other Options Are Wrong:

  • "finally" alone ignores the catch and trailing print in main.
  • "exception finished" ignores that finally executes in aMethod before control returns.
  • "Compilation fails" is incorrect; the code is valid.


Common Pitfalls:
Assuming finally runs only if no exception is thrown; or assuming catch in main prints before the callee's finally.



Final Answer:
finally exception finished

More Questions from Exceptions

Discussion & Comments

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