Using a return statement inside a finally block will override any other return statement or thrown exception from the try block and all defined catch blocks. Code execution in the parent stack will continue as if the exception was never thrown.
Frankly this is a good design decision because it means I can optionally dismiss all thrown exceptions from 1 or more catch blocks in one place, without having to nest my whole try block inside an additional (and otherwise needless) try/catch block.
This is the same behavior as Java, whereas C# throws a compile time error when a return statement exists inside a finally block. So I figured it was worth pointing out to PHP devs who may not have any exposure to finally blocks or how other languages do it.
<?php
function asdf()
{
try {
throw new Exception('error');
}
catch(Exception $e) {
echo "An error occurred";
throw $e;
}
finally {
return "\nException erased";
}
}
try {
echo asdf();
}
catch(Exception $e) {
echo "\nResult: " . $e->getMessage();
}
?>
The output from above will look like this:
An error occurred
Exception erased
Without the return statement in the finally block it would look like this:
An error occurred
Result: error