Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Exceptions and Errors

The PHP finally block in depth

How PHP finally works: when it runs, how it interacts with return, break and exceptions, what overrides what, and patterns for reliable cleanup of resources.

A finally block runs after its try (and any catch) no matter how control leaves: normal completion, a return, a break or continue, a caught exception or an exception nobody catches. Its job is cleanup that must always happen, such as closing a file, releasing a lock or ending a transaction.

A try needs at least one catch or a finally, so try { } finally { } without any catch is valid. The exception then continues upward after the cleanup has run.

PHP
$handle = fopen($path, "r");
try {
    process($handle);
} finally {
    fclose($handle);
}

Try it

PHP When finally runs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Overriding return values and replacing exceptions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Rules to remember

  1. The return value is fixed first. return $n evaluates $n before finally runs, so changing $n inside finally does not change what was returned (the second example). Returning from finally replaces it.
  2. A return in finally swallows exceptions. The pending exception is discarded and the function returns normally. This is almost always a bug; avoid return, break and continue in finally.
  3. An exception thrown in finally replaces the pending one, but PHP attaches the replaced exception as the new one's previous, so nothing is lost.
  4. Jumps run finally too. break, continue and goto out of a try execute the finally first.
  5. Not guaranteed on process death: exit() ends the script without running finally blocks (shutdown functions and destructors do run), and so do fatal errors, a killed process or a timeout.
  6. Generators: finally inside a generator runs when the generator completes or is destroyed while suspended.

Patterns

  • Pair acquire with release: open the resource immediately before try, close it in finally. If fopen() itself fails, there is nothing to close.
  • Restore state: switch a setting, try the work, put the old value back in finally.
  • Transactions: commit at the end of try, roll back in a catch that rethrows, and release locks in finally.
  • Prefer objects with destructors or small helpers like withFile($path, fn($h) => ...) when many call sites need the same cleanup.
  • Keep finally short and safe. If cleanup can fail, that failure hides the original one; log it instead of throwing.