0
0
PHPprogramming~20 mins

Finally block behavior in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Finally Block Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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";
?>
AStart Finally
BFinally Start
CStart End
DStart
Attempts:
2 left
💡 Hint
Remember that the finally block runs even if the try block returns early.
Predict Output
intermediate
2: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";
?>
ATry Catch Done
BTry Finally Catch Done
CTry Catch Finally Done
DTry Done Finally Catch
Attempts:
2 left
💡 Hint
The finally block runs after catch, before continuing.
Predict Output
advanced
2: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();
?>
A2
B1
CNULL
DFatal error
Attempts:
2 left
💡 Hint
A return in finally overrides any previous return.
Predict Output
advanced
2: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";
?>
AFinally Try Fatal error: Uncaught Exception
BTry Finally End
CTry End Finally
DTry Finally Fatal error: Uncaught Exception
Attempts:
2 left
💡 Hint
Exception in finally block interrupts normal flow.
🧠 Conceptual
expert
2: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 ";
}
?>
A1 time
B2 times
C3 times
D0 times
Attempts:
2 left
💡 Hint
Each try has its own finally block that always runs.