The finally block lets you run code that must happen no matter what, even if there was an error or the program returned early.
Finally block behavior in PHP
Introduction
Syntax
PHP
<?php try { // code that might cause an error } catch (Exception $e) { // code to handle the error } finally { // code that always runs } ?>
The finally block runs after try and catch, no matter what.
If there is no catch block, finally still runs after try.
Examples
try code and then the finally code, even without a catch.PHP
<?php try { echo "Start\n"; } finally { echo "Always runs\n"; } ?>
finally block.PHP
<?php try { throw new Exception("Error!"); } catch (Exception $e) { echo "Caught: " . $e->getMessage() . "\n"; } finally { echo "Cleanup code\n"; } ?>
finally block runs even if the try block returns early.PHP
<?php try { return "From try"; } finally { echo "Finally runs even with return\n"; } ?>
Sample Program
This program shows that the finally block runs even if the catch block returns a value.
PHP
<?php function testFinally() { try { echo "Trying...\n"; throw new Exception("Oops"); } catch (Exception $e) { echo "Caught exception: " . $e->getMessage() . "\n"; return "Returned from catch"; } finally { echo "Finally block runs no matter what\n"; } } $result = testFinally(); echo "Result: $result\n"; ?>
Important Notes
The finally block is useful for cleanup tasks that must happen no matter what.
If both catch and finally have return statements, the finally return overrides the catch return.
Summary
The finally block always runs after try and catch, even if there is an error or a return.
Use finally to clean up resources or run important code that must not be skipped.
Practice
1. What is the main purpose of the
finally block in PHP exception handling?easy
Solution
Step 1: Understand the roles of try, catch, and finally
Thetryblock contains code that may throw exceptions,catchhandles those exceptions, andfinallyruns code after both regardless of exceptions.Step 2: Identify the unique role of finally
Thefinallyblock always executes, even if an exception is not thrown or is caught, making it ideal for cleanup.Final Answer:
To execute code regardless of whether an exception was thrown or caught -> Option CQuick Check:
finally always runs = D [OK]
Hint: finally always runs after try/catch blocks [OK]
Common Mistakes:
- Confusing finally with catch block
- Thinking finally only runs on exceptions
- Assuming finally stops script execution
2. Which of the following is the correct syntax for using a
finally block in PHP?easy
Solution
Step 1: Recall PHP try-catch-finally syntax
The correct syntax requirestry, thencatchwith exception parameter, thenfinallywithout parameters or parentheses.Step 2: Check each option for syntax errors
try { /* code */ } catch (Exception $e) { /* handle */ } finally { /* cleanup */ } matches correct syntax. try { /* code */ } finally (Exception $e) { /* cleanup */ } wrongly uses parameters in finally. try { /* code */ } catch { /* handle */ } finally { /* cleanup */ } misses exception variable in catch. try { /* code */ } catch (Exception $e) { /* handle */ } finally() { /* cleanup */ } wrongly uses parentheses after finally.Final Answer:
try { /* code */ } catch (Exception $e) { /* handle */ } finally { /* cleanup */ } -> Option DQuick Check:
Correct try-catch-finally syntax = B [OK]
Hint: finally block has no parameters or parentheses [OK]
Common Mistakes:
- Adding parameters to finally block
- Omitting exception variable in catch
- Using parentheses after finally keyword
3. What will be the output of the following PHP code?
function test() {
try {
echo "Try block\n";
return 1;
} catch (Exception $e) {
echo "Catch block\n";
} finally {
echo "Finally block\n";
}
}
echo test();medium
Solution
Step 1: Trace the try block execution
Thetryblock prints "Try block" and then returns 1 immediately.Step 2: Understand finally block runs after return
Even though return is called, thefinallyblock executes next, printing "Finally block" before the function returns.Final Answer:
Try block Finally block 1 -> Option BQuick Check:
finally runs after return = A [OK]
Hint: finally runs even after return statement [OK]
Common Mistakes:
- Assuming finally does not run after return
- Expecting catch block to run without exception
- Misordering output lines
4. Identify the error in the following PHP code snippet:
try {
throw new Exception("Error!");
} catch (Exception $e) {
echo "Caught: " . $e->getMessage();
} finally {
echo "Cleanup";
}medium
Solution
Step 1: Check syntax and logic of try-catch-finally
The try block throws an exception, the catch block catches it and prints the message, and finally prints "Cleanup".Step 2: Verify if any syntax or runtime errors exist
All blocks are correctly formed, exception variable is present, and finally block is valid without return.Final Answer:
There is no error; the code runs correctly -> Option AQuick Check:
Valid try-catch-finally syntax = A [OK]
Hint: finally block is optional and valid without return [OK]
Common Mistakes:
- Thinking finally requires return statement
- Missing exception variable in catch
- Misplacing throw statement
5. Consider this PHP function:
What will be the output when calling
function process() {
try {
echo "Start\n";
throw new Exception("Oops");
return 10;
} catch (Exception $e) {
echo "Caught: " . $e->getMessage() . "\n";
return 20;
} finally {
echo "Finally runs\n";
return 30;
}
}
echo process();What will be the output when calling
process()?hard
Solution
Step 1: Trace the try block and exception
The try block prints "Start", then throws an exception, so the return 10 is skipped.Step 2: Catch block runs and returns 20
The catch block prints "Caught: Oops" and returns 20, but before returning, finally block executes.Step 3: Finally block runs and overrides return
The finally block prints "Finally runs" and returns 30, which overrides previous returns.Final Answer:
Start Caught: Oops Finally runs 30 -> Option AQuick Check:
finally return overrides others = C [OK]
Hint: Return in finally overrides try/catch returns [OK]
Common Mistakes:
- Ignoring that finally return overrides catch return
- Assuming catch return is final
- Missing output order of prints
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
