Skip to content

33: Move Returns Out of finally Blocks

Keep resource cleanup in finally and return the result on the success path. Returning from finally is deprecated in PHP 8.6 because it can replace an earlier return or suppress an exception.

  • PHP 8.6 CLI. Confirm the version with php --version.
  • Review the previous chapter if you’re following the series in order.

Allow about 10 minutes for the walkthrough and exercise.

A runnable return-in-finally.php example.

Run the following from the root of the Code with PHP repository.

Terminal window
php code/php-8-6/33-return-in-finally/return-in-finally.php
return-in-finally.php
<?php
declare(strict_types=1);
function writeNote(string $note, bool $simulateFailure = false): int
{
$stream = fopen('php://temp', 'w+');
if ($stream === false) {
throw new RuntimeException('Cannot open temp stream');
}
try {
if ($simulateFailure) {
throw new RuntimeException('Write rejected');
}
$written = fwrite($stream, $note);
if ($written === false || $written !== strlen($note)) {
throw new RuntimeException('Incomplete write');
}
return $written;
} finally {
fclose($stream);
}
}
echo writeNote('hello'), " bytes\n";
try {
writeNote('hello', true);
} catch (RuntimeException $error) {
echo $error->getMessage(), PHP_EOL;
}
5 bytes
Write rejected

PHP executes finally as control leaves try, including when an exception is propagating. With cleanup alone in that block, callers still receive the successful result or the original exception.

Pass an empty string as valid input. Confirm that it prints a zero byte count on that path and still propagates exceptions when explicitly asked to fail.

Continue with Move Results and Generators Out of Object Lifecycles.