Search code examples
phptry-catch-finally

Programming without "finally"


I don't have the required version of PHP that supports finally, so I am wondering if this:

try {
    work();
} catch (Exception $e) {
    cleanup();
    throw $e;
}

cleanup();

is exactly the same as

try {
    work();
} finally {
    cleanup();
}

Solution

  • The point of the finally block is to execute regardless of what happens in the try block, or in following catch cases. So if you think about it, the code in the finally block is executed either after a successful try block execution, or after any exception was thrown. So if you write it just as you did in your solution, then you do indeed mimic the situation exactly. If there is no exception, the code after the try/catch structure is executed; and if there is an exception—any exception—you also execute it.

    I think the only situation which the finally support may rescue you from, which your version inherently can’t, is when you are actually aborting the outer execution stack early. For example if this code is inside a function and you are returning from within the try block, then the finally would still be executed, but in your manual implementation it of course couldn’t.

    So if you make sure that you do not leave early, then yes, it should work in the same way.

    There are not many ways to leave a function early that don’t throw an exception; return is the most obvious and aborting the program with exit, die or similar would be another.