Why use the "finally" keyword?

Short Answer

Finally blocks are guaranteed to run no matter what happens inside of the try and catch blocks, before allowing the program to crash.

This is sort of explained here: https://www.php.net/manual/en/language.exceptions.php though the explanation isn't particularly detailed.

Some More Detail

One example that comes to the top of my head is if you are dealing with input/output streams or something similar that has to be closed after use in order to avoid a memory leak. To use your example:

try {
  memoryUser.startReading(someFileOrSomething);
}
catch (CustomException $customException) {
  // handle custom error
}
catch (Exception $exception) {
  // handle the error
  invisibleBug.whoops(); // i.e. something goes wrong in this block
}

memoryUser.Close(); // because something went wrong in the catch block,
                    // this never runs, which, in this case, causes a memory leak

In this case, wrapping the memoryUser.Close(); in a finally block would ensure that that line would run before the rest of the program exploded, preventing the memory leak even in an otherwise catastrophic failure.

TL;DR

So a lot of the time, people put the finally block there to ensure an important line runs, even if they overlooked something in the catch blocks. This is how I've always seen it used.

Hopefully this helps :)


What's special about a finally {} block is that it will always run at the end of the try {} block.

  • It will run if the code in the try {} block completes successfully.

  • It will run if the code in the try {} block throws an exception that was caught by a catch {}. (The finally {} runs after the catch {}.)

  • It will run if the code in the try {} block throws an exception that wasn't handled by any catch {} block, or if there weren't any at all. (The finally {} block runs before the exception is propagated to the caller.)

  • It will run if the code in the try {} block throws an exception, and the code in the catch {} throws another exception (or rethrows the same exception).

  • It will even run if the code in the try {} block, or in a catch {} block, uses return. (Just as with an uncaught exception, the finally {} runs before the function actually returns.) The finally {} block can even use return itself, and its return value will override the value that the other block tried to return!

(There is one edge case where a finally {} block won't run, and that's if the entire process is destroyed, e.g. by being killed, or by calling exit() or die().)