Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP Interaction between finally and return
In PHP, there is a peculiar behavior of the finally block when either the try block or catch block contains a return statement. Normally, a return statement causes program control to go back to the calling position. However, in functions with try/catch blocks containing return statements, the finally block is always executed first before returning.
Example
In the following example, the div() function has a try-catch-finally construct. The try block returns the result of division when no exception occurs. In case of an exception, the catch block returns an error message. However, in either case, the statement in the finally block is executed first −
<?php
function div($x, $y){
try {
if ($y == 0)
throw new Exception("Division by 0");
else
$res = $x / $y;
return $res;
}
catch (Exception $e){
return $e->getMessage();
}
finally{
echo "This block is always executed<br>";
}
}
$x = 10;
$y = 0;
echo div($x, $y);
?>
This block is always executed Division by 0
Testing with Valid Division
When we change the value of $y to 5, the division executes successfully, but the finally block still runs first −
<?php
function div($x, $y){
try {
if ($y == 0)
throw new Exception("Division by 0");
else
$res = $x / $y;
return $res;
}
catch (Exception $e){
return $e->getMessage();
}
finally{
echo "This block is always executed<br>";
}
}
$x = 10;
$y = 5;
echo div($x, $y);
?>
This block is always executed 2
Key Points
- The finally block executes before any return statement takes effect
- This behavior occurs regardless of whether the return is in try or catch block
- The finally block cannot modify the return value itself
Conclusion
PHP's finally block always executes before return statements, making it perfect for cleanup operations. This ensures critical code runs regardless of how the function exits, whether through normal execution or exception handling.
