Return From Finally

ID

php.return_from_finally

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Php

Tags

CWE:584, exception-handling, reliability

Description

Reports a return statement inside a finally block. Returning from finally overrides whatever the try or catch block was about to return and, worse, silently discards any exception that was still propagating, hiding the original failure.

Rationale

A finally block runs unconditionally as the try/catch unwinds. If it executes a return, that return wins: a value being returned from try is replaced, and — most dangerously — an in-flight exception is abandoned without a trace, so the caller sees a normal return where an error actually occurred. The result is lost stack traces and bugs that are extremely hard to diagnose. Cleanup is the only job a finally block should do.

<?php
function read(): int
{
    try {
        return $this->doRead(); // its value (or any exception) is discarded below
    } finally {
        return 0;               // FLAW — swallows the exception and overrides the result
    }
}

function readClean(): int
{
    try {
        return $this->doRead();
    } finally {
        $this->close();         // OK — finally only performs cleanup
    }
}

Remediation

Remove the return from the finally block and keep only cleanup code there. If a specific value must be returned, compute it in the try or catch block and let that return stand.