Search the blog

The finally keyword relates to try and catch blocks. The PHP website describes finally thus:

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.

At first it may seem like there is no use for finally. However, it is extremely useful if you want to return something from a function but still call some other code regardless — such as logging or closing a file stream. As the above description states finally is called “before normal execution resumes”.

This code demonstrates it:

function exceptionTest1() {

    try {

        throw new Exception('error');

    } catch (Exception $e) {

        return false;

    }

    echo 'finally ';

}

var_dump(exceptionTest1()); // just returns false

function exceptionTest2() {

    try {

        throw new Exception('error');

    } catch (Exception $e) {

        return false;

    } finally {

        echo 'finally ';

    }

}

var_dump(exceptionTest2()); // echoes 'finally' and returns false

function exceptionTest3() {

    try {

        throw new Exception('error');

    } catch (Exception $e) {

        return false;

    } finally {

        return true;

    }

}

var_dump(exceptionTest3()); // returns true
Tim Bennett is a Leeds-based web designer from Yorkshire. He has a First Class Honours degree in Computing from Leeds Metropolitan University and currently runs his own one-man web design company, Texelate.