Challenge - 5 Problems
Finally Block Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this PHP code with try-finally?
Consider the following PHP code snippet. What will it output when run?
PHP
<?php try { echo "Start "; return; } finally { echo "Finally "; } echo "End"; ?>
Attempts:
2 left
💡 Hint
Remember that the finally block runs even if the try block returns early.
✗ Incorrect
In PHP, the finally block executes even if the try block has a return statement. So 'Start ' is printed, then finally block prints 'Finally '. The code after try-finally is not executed because of return.
❓ Predict Output
intermediate2:00remaining
Output when exception is thrown and caught with finally
What will this PHP code output?
PHP
<?php try { echo "Try "; throw new Exception("Error"); } catch (Exception $e) { echo "Catch "; } finally { echo "Finally "; } echo "Done"; ?>
Attempts:
2 left
💡 Hint
The finally block runs after catch, before continuing.
✗ Incorrect
The try block prints 'Try ', then throws an exception. The catch block prints 'Catch '. The finally block always runs, printing 'Finally '. After that, the code prints 'Done'.
❓ Predict Output
advanced2:00remaining
What happens if finally block returns a value?
What will this PHP code output?
PHP
<?php function test() { try { return 1; } finally { return 2; } } echo test(); ?>
Attempts:
2 left
💡 Hint
A return in finally overrides any previous return.
✗ Incorrect
In PHP, if the finally block contains a return statement, it overrides the return from the try block. So the function returns 2.
❓ Predict Output
advanced2:00remaining
Output when exception thrown in finally block
What will this PHP code output?
PHP
<?php try { echo "Try "; } finally { echo "Finally "; throw new Exception("Error in finally"); } echo "End"; ?>
Attempts:
2 left
💡 Hint
Exception in finally block interrupts normal flow.
✗ Incorrect
The try block prints 'Try '. The finally block prints 'Finally ' then throws an exception. The exception is uncaught, so script stops with fatal error. 'End' is not printed.
🧠 Conceptual
expert2:00remaining
How many times does finally block execute in nested try-finally?
Consider this PHP code. How many times will the finally blocks execute?
PHP
<?php try { try { echo "Inner try "; } finally { echo "Inner finally "; } } finally { echo "Outer finally "; } ?>
Attempts:
2 left
💡 Hint
Each try has its own finally block that always runs.
✗ Incorrect
The inner try block runs and prints 'Inner try '. Its finally block runs printing 'Inner finally '. Then the outer finally block runs printing 'Outer finally '. So finally blocks run twice.