2

I was wondering if the following program flow will prevent the finally from being run in this try-catch-finally block due to a return in the try.

Please excuse poor error checking and sanitisation, this is just a mock:

function doLogin() {

    $dbh = new PDO('mysql:host=localhost;dbname=test', "root", "");
    $errors = array();
    $loginSuccess = false;

    try {
        $query = $dbh->prepare('SELECT *
                                FROM users
                                WHERE username = :username');
        $query->bindParam(':username', $_POST['username'], PDO::PARAM_STR);
        $result = $query->fetch(PDO::FETCH_ASSOC);
        if (!password_verify($_POST['password'], $result['password'])) {
            array_push($errors, 'Invalid password.');
            return; // will this return prevent the finally from being run?
        }
        else {
            $loginSuccess = true;
        }
    }
    catch (PDOException $pdoEx) {
        echo 'Error occurred ' . $pdoEx->getMessage();
    }
    finally {
        $dbh = null;
    }

}

Code is pretty poorly written, but hopefully you understand my point.

nabir
  • 1,447
  • 2
  • 12
  • 17
  • Possible duplicate: http://stackoverflow.com/questions/3837994/javascript-try-catch-return-statement – Vince Jun 18 '14 at 15:15
  • 3
    Why not write a quick example program to test it? – Mr. Llama Jun 18 '14 at 15:16
  • @VinceEmigh - That question is regarding Javascript. Although PHP and Javascript have some similarities, they're absolutely not the same language and may handle things differently. – Mr. Llama Jun 18 '14 at 15:17
  • @Mr.Llama I'll get to doing that, just wanted to quickly pop in and ask SO just in case it was very basic program flow knowledge. – nabir Jun 18 '14 at 15:18

1 Answers1

1

The answer is yes, the code in finally will be run.

For example:

function example() {
    try {
        return true;
    }
    catch(Exception $e){
        echo "error";    
    }
    finally{
        return false;
    }
}
var_dump( example() );

Outputs:

bool(false)

It's also (hiddenly) stated in the docs:

In PHP 5.5 and later, a finally block may also be specified after the catch blocks. Code within the finally block will always be executed after the try and catch blocks, regardless of whether an exception has been thrown, and before normal execution resumes.

To my understanding the try block finishes with the return statement. The normal execution is "paused" and the finally executed.

idmean
  • 14,540
  • 9
  • 54
  • 83
  • Thanks, and yep just did a quick test myself (which I should have done from the beginning) [here.](http://sandbox.onlinephpfunctions.com/code/fc5a8020df2a3b2447f7c16bda3f5062d4320b99) – nabir Jun 18 '14 at 15:30