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.
$handle = fopen($path, "r"); try { process($handle); } finally { fclose($handle); }
Try it
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.
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
- The return value is fixed first.
return $nevaluates$nbeforefinallyruns, so changing$ninsidefinallydoes not change what was returned (the second example). Returning fromfinallyreplaces it. - A
returninfinallyswallows exceptions. The pending exception is discarded and the function returns normally. This is almost always a bug; avoidreturn,breakandcontinueinfinally. - An exception thrown in
finallyreplaces the pending one, but PHP attaches the replaced exception as the new one'sprevious, so nothing is lost. - Jumps run
finallytoo.break,continueandgotoout of atryexecute thefinallyfirst. - Not guaranteed on process death:
exit()ends the script without runningfinallyblocks (shutdown functions and destructors do run), and so do fatal errors, a killed process or a timeout. - Generators:
finallyinside 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 infinally. Iffopen()itself fails, there is nothing to close. - Restore state: switch a setting,
trythe work, put the old value back infinally. - Transactions: commit at the end of
try, roll back in acatchthat rethrows, and release locks infinally. - Prefer objects with destructors or small helpers like
withFile($path, fn($h) => ...)when many call sites need the same cleanup. - Keep
finallyshort and safe. If cleanup can fail, that failure hides the original one; log it instead of throwing.
Related
try,catch,finally,throw, Custom exceptions,Exception,fopen()- Lessons: Exceptions, File handling