return Inside finally Is Deprecated in PHP 8.6, and Your Laravel Cleanup Code Probably Does It

PHP 8.6 deprecates return inside finally. Why it was always a bug, the Laravel cleanup code that quietly does it, and the two-line rewrite that fixes it.

Steven Richardson
Steven Richardson
· 8 min read

You bump the image to PHP 8.6, the logs fill with a deprecation you have never seen, and the line it points at looks completely innocent — a finally that deletes a temp file and returns a download response. The deprecation is not style policing. It is a bug report: that method has been throwing away exceptions for years, and nobody noticed, because the return in finally quietly outranked them.

PHP 8.6.0 shipped on 19 November 2026, so this is live now. Here is what the php return in finally deprecated notice actually means and how to clear every one of them.

Reproduce the return in finally deprecation on PHP 8.6#

The Deprecations for PHP 8.6 RFC passed 39–3–4 and added a compile-time deprecation wherever a finally block contains a return. Runtime behaviour is unchanged — the construct still does exactly what it did in 8.5 — but the engine now tells you about it the moment the file is compiled. Paste this into php -r or a route and you will see it.

<?php

function getConfig(): array
{
    try {
        return loadConfig(); // throws if the file is missing
    } finally {
        return []; // the exception is gone, the caller just gets []
    }
}

The notice reads:

Deprecated: Returning from a finally block is deprecated

Two things matter about compile time. First, you get the notice even when the finally never executes in that request — opcache will surface it on first compile of the file. Second, you cannot reach it with a runtime guard, so there is no way to conditionally silence it. It is flagged for removal in PHP 9, so this is a fix-it-now deprecation, not a live-with-it one. Add it to the list alongside everything else in the Laravel PHP 8.6 upgrade checklist.

See which exception the finally discards#

Before rewriting anything, understand the defect the deprecation is describing, because it changes how you treat the fix. When try or catch exits — by returning a value or by throwing — a return in finally overrides it. A returned value is overwritten. A thrown exception is discarded outright: no log entry, no reporting to Sentry, no stack trace, nothing.

<?php

function readManifest(string $path): array
{
    $handle = fopen($path, 'r');

    try {
        // Throws JsonException on malformed input.
        return json_decode(stream_get_contents($handle), true, 512, JSON_THROW_ON_ERROR);
    } finally {
        fclose($handle);

        return []; // Swallows JsonException. Caller sees an empty manifest.
    }
}

The happy path is identical either way, which is exactly why this survives code review. The failure path is where it bites: a corrupt manifest becomes an empty array, the import "succeeds" with zero rows, and the incident ticket three days later points at the import job rather than the parse. That is the opposite of what a well-behaved failure should do — an exception you have gone to the trouble of giving render and report context is worth precisely nothing if a finally eats it before the handler sees it.

Rewrite a return in finally into a plain return#

The rewrite is mechanical and takes two lines. Assign the result to a variable inside try/catch, leave finally holding only side effects, and return after the whole block. Behaviour is identical when nothing throws, and correct when something does.

<?php

function readManifest(string $path): array
{
    $handle = fopen($path, 'r');

    try {
        $manifest = json_decode(stream_get_contents($handle), true, 512, JSON_THROW_ON_ERROR);
    } finally {
        fclose($handle); // Runs on both the success and the throw path.
    }

    return $manifest;
}

If the caller genuinely wants a default instead of an exception, that is a catch, not a finally — and writing it as a catch forces you to name the exception class you are willing to absorb, which is the entire point:

<?php

try {
    $manifest = json_decode(/* ... */, flags: JSON_THROW_ON_ERROR);
} catch (JsonException) {
    $manifest = []; // A deliberate, narrow default.
} finally {
    fclose($handle);
}

return $manifest;

Replace hand-rolled cleanup with Laravel's own closures#

Most of the occurrences I find in Laravel codebases are not really about returning a value. They are about releasing something — a temp file, a lock, a transaction — and the return crept into finally because that is where the cleanup lived. In every one of those cases Laravel already owns the release, and deleting the try/finally entirely beats rewriting it.

Temp-file exports are the classic. Instead of this:

<?php

public function export(): BinaryFileResponse
{
    $path = storage_path('app/exports/'.Str::uuid().'.csv');

    try {
        $this->writer->write($path); // Can throw on a disk-full.
    } finally {
        Storage::delete($path);

        return response()->download($path); // Deprecated — and the file is gone.
    }
}

Use deleteFileAfterSend(), which Laravel runs after the response has been sent rather than before:

<?php

public function export(): BinaryFileResponse
{
    $path = storage_path('app/exports/'.Str::uuid().'.csv');

    $this->writer->write($path);

    return response()->download($path)->deleteFileAfterSend(true);
}

The same applies to locks. A hand-rolled try/finally that acquires a lock, does work, and releases in finally is Cache::lock() written the long way:

<?php

// Laravel releases the lock whether the closure returns or throws.
return Cache::lock('reconcile:'.$account->id, 60)->block(5, function () use ($account) {
    return $this->reconcile($account);
});

And a hand-rolled transaction wrapper with a rollback in finally is DB::transaction(), which commits on return and rolls back on throw. If you are already in that part of the codebase, it is worth checking that the work you queue inside it is dispatched after commit too — the two bugs tend to live in the same file. For the file-handling side, the same argument runs through the Laravel file storage and uploads guide.

Find every occurrence with PHPStan#

You do not need a custom rule for this one. PHPStan has shipped OverwrittenExitPointByFinallyRule for years, under the error identifier finally.exitPoint, and it reports a return or throw in try/catch that a finally overwrites. Run it at level 0 or above and it will find them all without any configuration.

# phpstan.neon
parameters:
    level: 6
    paths:
        - app
        - routes
    # Do NOT add finally.exitPoint to ignoreErrors during the 8.6 upgrade.

Where the behaviour really is intentional — rare, but it happens in test doubles and shutdown handlers — suppress it per line rather than globally:

// @phpstan-ignore finally.exitPoint

Rector does not ship a rule for this as of 8.6's release, because the rewrite is not always safe to automate: moving a return out of finally changes what the function returns when try throws, which is the whole point. If you want it mechanised anyway, this is a good candidate for writing a custom Rector rule that flags rather than fixes, in the same spirit as a custom PHPStan rule enforcing your own conventions.

Fail CI on deprecations during the upgrade#

Static analysis catches the shapes it can see. Deprecations emitted by vendor code and dynamically included files need the test suite. For the duration of the 8.6 upgrade, turn deprecations into failures so a new one cannot merge.

<!-- phpunit.xml — Pest reads this file too -->
<phpunit
    failOnDeprecation="true"
    failOnWarning="true"
    failOnNotice="true"
>

Expect a noisy first run. Triage into two piles: deprecations in your own code, which you fix now, and deprecations from packages, which you ignore by path until an upstream release lands. Keep the flag on until the upgrade branch is merged, then decide whether to keep it permanently — I do, because the next round of deprecations always arrives.

Watch for these edge cases#

A few things that are easy to get wrong.

throw in finally is not deprecated. The RFC only covers return. A throw in finally discards an in-flight exception just as thoroughly, and PHPStan still reports it as finally.exitPoint, but PHP 8.6 will not say a word.

Generators count. A yield is fine, but a bare return inside a finally in a generator body is still a return and still deprecated.

list() is deprecated in the same RFC. If you are auditing for one, audit for the other — list($a, $b) becomes [$a, $b] with no behaviour change. Companion deprecations such as the non-canonical function aliases like is_double() and spl_object_hash() landed in the same release, so one pass can clear all three.

Opcache hides it in production. Because the notice is emitted at compile time, a warmed opcache means you may see each deprecation exactly once after a deploy and never again. Do not read a quiet log as a clean codebase — trust the static analysis, not the absence of notices.

Wrapping Up#

Treat every one of these notices as a defect report rather than a lint warning: find the exception that finally has been eating, fix the control flow, and prefer DB::transaction(), Cache::lock() and deleteFileAfterSend() over hand-rolled cleanup. Run PHPStan with finally.exitPoint unignored, flip failOnDeprecation on, and the whole class of bug is gone in an afternoon. Work through the rest of the release with the Laravel PHP 8.6 upgrade checklist, and if your CI pipeline is doing all this in one command already, Duster's Pint, PHPStan and Rector setup is where to wire the gate in.

FAQ#

Why is return inside finally deprecated in PHP 8.6?

Because it silently discards failures. When try or catch exits by throwing, a return in the finally block overrides that exit and the exception vanishes with no notice, warning or trace. The RFC authors argued that nothing is lost by deprecating it, since the same result can always be expressed with a variable and a trailing return, and removing it makes a whole class of invisible bug impossible.

Does return in finally swallow exceptions?

Yes, completely. If try throws and finally returns, the caller receives the returned value and never learns that an exception occurred. Nothing is logged and nothing reaches your exception handler, which is why the failure usually surfaces much later as a wrong value or an action that quietly never happened.

How do I rewrite a return inside a finally block?

Assign the result to a variable inside try (and inside catch, if you have one), leave only side effects such as closing handles or releasing locks in finally, then return the variable after the whole block. Behaviour is identical when nothing throws and correct when something does. If you genuinely want a fallback value instead of an exception, write that as a catch for a specific exception class rather than a return in finally.

Will my Laravel app break on PHP 8.6 if I use return in finally?

No. Runtime behaviour is unchanged in 8.6, so the code still does exactly what it did before — you get a deprecation notice and nothing else. The construct is slated for removal in PHP 9, though, so it will break eventually, and in the meantime the notice is pointing at code that is probably already losing exceptions.

Can PHPStan or Rector find return statements inside finally?

PHPStan can, out of the box. The rule is OverwrittenExitPointByFinallyRule and the error identifier is finally.exitPoint, reported from level 0 upwards with no configuration required. Rector does not ship an equivalent rule, because the rewrite changes what the function returns on the failure path and is not safe to apply blindly, so a custom rule that reports rather than refactors is the better option there.

Steven Richardson
Steven Richardson

CTO at Digitonic. Writing about Laravel, architecture, and the craft of leading software teams from the west coast of Scotland.