Returning from finally Block is Deprecated in PHP 8.6

Returning from finally Block is Deprecated in PHP 8.6

In PHP, the try/catch/finally construct is commonly used to guarantee cleanup actions, such as closing a file handle. The finally block runs no matter how the try block ends. PHP has always allowed a return statement inside the finally block as well, even though such a return silently discards an exception thrown by the try or catch block, or overwrites the value which they returned.

Since PHP 8.6, using the return statement inside a finally block is deprecated, because it is a pattern which easily leads to subtle bugs. Consider the following function which writes data to a file and returns a success flag:

<?php

function saveFile(array $data, string $path): bool
{
    $handle = fopen($path, 'ab');
    try {
        fwrite($handle, json_encode($data, JSON_THROW_ON_ERROR));
    } catch (Throwable) {
        return false;
    } finally {
        fclose($handle);

        return true;
    }
}

var_dump(saveFile(['value' => 'Hello'], 'test.txt')); // true
var_dump(saveFile(['value' => NAN], 'test.txt')); // true

Output:

Deprecated: Returning from a finally block is deprecated in main.php on line 13
bool(true)
bool(true)

The second call fails, because NAN cannot be encoded as JSON and json_encode throws a JsonException. The catch block handles the exception and returns false, but the return true inside the finally block replaces that value. The function reports success, nothing is written to the file and the failure leaves no trace.

The deprecation notice is emitted at compile time, so it appears once for each declaration, as soon as the file is compiled. A function which is never called still produces it.

The example can be fixed by reserving the finally block strictly for cleanup and moving the return statements into the try and catch blocks:

<?php

function saveFile(array $data, string $path): bool
{
    $handle = fopen($path, 'ab');
    try {
        fwrite($handle, json_encode($data, JSON_THROW_ON_ERROR));

        return true;
    } catch (Throwable) {
        return false;
    } finally {
        fclose($handle);
    }
}

var_dump(saveFile(['value' => 'Hello'], 'test.txt')); // true
var_dump(saveFile(['value' => NAN], 'test.txt')); // false

The failed call now returns false, while fclose still runs for both calls.

Leave a Comment

Cancel reply

Your email address will not be published.