Which of the following options is true for the following program: try { if (choice) { while (true) } else { system .exit(1): } }finally { codetocleanup(); }
Reveal answer
Fill a bubble to check yourself
Which of the following options is true for the following program: try { if (choice) { while (true) } else { system .exit(1): } }finally { codetocleanup(); }
Runtime Exception
finally block will be executed
finally block will not be executed
Compilation error in else block
System.exit() terminates the JVM immediately, preventing the finally block from executing. Additionally, the while(true) loop in the if branch never exits, so the finally block would never be reached in that case either. Only if neither branch executes would finally run, but the structure guarantees one of them does.
'Finally block will not be executed' is correct, in both possible paths through the code. If choice is true, the code enters an infinite while(true) loop with no break, so control never reaches the end of the try block and the finally clause is never reached at all — the thread simply loops forever. If choice is false, System.exit(1) is called, which immediately terminates the JVM; unlike a normal return or exception, System.exit() does not run pending finally blocks during shutdown. So regardless of which branch is taken, codetocleanup() in finally never executes. (Note the snippet as given has minor typos — lowercase 'system.exit' and a colon instead of a semicolon, and the while loop appears to be missing a body statement — but the underlying behavior being tested, infinite loop vs. System.exit both bypassing finally, is the intended concept.)