try, finally, and cleanup
suggest changeCode that acquires something (a file handle, a lock, a database transaction, a temporary file, a changed global setting) must release it again, even when an exception is thrown halfway through. PHP's tool for that is the finally block.
A finally block runs when control leaves the try block, no matter how it leaves:
- the
tryblock finishes normally - an exception is thrown, whether it is caught or not
return,breakorcontinuejumps out of thetryorcatchblock
The basics of try / catch are covered in Exception and Error handling. This article is about finally and about patterns for reliable cleanup.
When finally runs
<?php
function run(string $mode): string
{
echo "start $mode\n";
try {
if ($mode === 'throw') {
throw new RuntimeException('failed');
}
if ($mode === 'return') {
return "early return";
}
echo " try finished normally\n";
} catch (RuntimeException $e) {
echo " caught: {$e->getMessage()}\n";
} finally {
echo " finally runs\n";
}
return "end of function";
}
foreach (['normal', 'throw', 'return'] as $mode) {
$result = run($mode);
echo "=> $result\n";
}
Output:
start normal
try finished normally
finally runs
=> end of function
start throw
caught: failed
finally runs
=> end of function
start return
finally runs
=> early return
In the return case finally runs after the return expression is evaluated but before the function actually returns to the caller.
try / finally without catch
You don't need a catch block. try / finally on its own is the most common cleanup pattern: release the resource here, and let the exception travel up to whoever can handle it.
<?php
function loadConfig(string $path): array
{
$fh = fopen($path, 'r');
if ($fh === false) {
throw new RuntimeException("cannot open $path");
}
try {
$json = stream_get_contents($fh);
return json_decode($json, true, flags: JSON_THROW_ON_ERROR);
} finally {
fclose($fh);
echo "file closed\n";
}
}
file_put_contents('good.json', '{"debug": true}');
file_put_contents('bad.json', '{"debug": tru');
var_dump(loadConfig('good.json'));
try {
loadConfig('bad.json');
} catch (JsonException $e) {
echo "JsonException: ", $e->getMessage(), "\n";
}
Output:
file closed
array(1) {
["debug"]=>
bool(true)
}
file closed
JsonException: Syntax error
Note where the resource is acquired: before the try. If fopen() fails there is nothing to close, so the finally block must not run. Putting fopen() inside the try would make finally call fclose(false), which throws a TypeError.
finally also runs when nobody catches the exception. The cleanup happens first, then PHP reports the uncaught exception:
<?php
try {
echo "working\n";
throw new RuntimeException('nobody catches this');
} finally {
echo "finally still runs\n";
}
Output:
working
finally still runs
Fatal error: Uncaught RuntimeException: nobody catches this in /app/uncaught.php:4
Stack trace:
#0 {main}
thrown in /app/uncaught.php on line 4
catch, rethrow, and finally
If a catch block throws (a new exception or the same one again), finally still runs before the new exception leaves the function:
<?php
function step(string $name, bool $fail = false): void
{
try {
echo "$name: working\n";
if ($fail) {
throw new RuntimeException("$name failed");
}
} catch (RuntimeException $e) {
echo "$name: handling, then rethrowing\n";
throw new LogicException("wrapped", previous: $e);
} finally {
echo "$name: finally\n";
}
}
try {
step('job', fail: true);
} catch (LogicException $e) {
echo "caller got: ", $e->getMessage(), " <- ", $e->getPrevious()->getMessage(), "\n";
}
Output:
job: working
job: handling, then rethrowing
job: finally
caller got: wrapped <- job failed
This is why "catch, clean up, rethrow" is rarely needed. Put the cleanup in finally and use catch only when you actually do something with the exception.
return and finally
Three rules, all visible in one example:
- A
returnintryevaluates its value first. Changing the variable infinallydoes not change what is returned. - A
returninfinallyreplaces the value returned fromtry. - A
returninfinallyalso discards an exception that is in flight.
<?php
function counter(): int
{
$n = 1;
try {
return $n; // the value 1 is captured here
} finally {
$n = 100; // too late, does not change the result
}
}
function override(): string
{
try {
return 'from try';
} finally {
return 'from finally'; // replaces the return value
}
}
function swallow(): string
{
try {
throw new RuntimeException('important error');
} finally {
return 'everything is fine'; // the exception is discarded
}
}
var_dump(counter());
var_dump(override());
var_dump(swallow());
Output:
int(1)
string(12) "from finally"
string(18) "everything is fine"
swallow() is a real bug pattern: the exception disappears without a trace. Never return from a finally block. Use finally for side effects (closing, unlocking, restoring) only.
Exceptions thrown inside finally
If the cleanup code itself throws while another exception is already in flight, the new exception replaces the original one. PHP doesn't lose the original completely: it is attached as the previous exception of the new one.
<?php
function process(): void
{
try {
throw new RuntimeException('disk full');
} finally {
throw new LogicException('cleanup failed');
}
}
try {
process();
} catch (Exception $e) {
echo get_class($e), ': ', $e->getMessage(), "\n";
$prev = $e->getPrevious();
echo 'previous: ', get_class($prev), ': ', $prev->getMessage(), "\n";
}
Output:
LogicException: cleanup failed
previous: RuntimeException: disk full
Still, the caller now catches a LogicException about cleanup when the real problem was a full disk. A catch (RuntimeException $e) higher up would not even match. When cleanup can fail, and the failure matters less than the original error, catch it inside finally:
<?php
class Connection
{
public function query(string $sql): never
{
throw new RuntimeException("query failed: $sql");
}
public function close(): void
{
throw new RuntimeException('connection already dropped');
}
}
function report(Connection $db): void
{
try {
$db->query('SELECT * FROM sales');
} finally {
try {
$db->close();
} catch (Throwable $cleanupError) {
// Log it, but let the original exception continue
echo "logged: ", $cleanupError->getMessage(), "\n";
}
}
}
try {
report(new Connection());
} catch (RuntimeException $e) {
echo "caller sees: ", $e->getMessage(), "\n";
}
Output:
logged: connection already dropped
caller sees: query failed: SELECT * FROM sales
break and continue
finally runs when break or continue leaves a try block inside a loop:
<?php
foreach ([1, 2, 3, 4] as $n) {
try {
if ($n === 2) {
continue;
}
if ($n === 4) {
break;
}
echo "processing $n\n";
} finally {
echo "cleanup after $n\n";
}
}
Output:
processing 1
cleanup after 1
cleanup after 2
processing 3
cleanup after 3
cleanup after 4
The opposite direction is not allowed: break, continue or goto that would jump out of a finally block is a compile error:
<?php
for ($i = 0; $i < 2; $i++) {
try {
} finally {
break;
}
}
Output:
Fatal error: jump out of a finally block is disallowed in /app/jump.php on line 5
Generators: finally runs when the generator is destroyed
A generator that holds a resource can use finally to release it. The block runs when the generator finishes, and also when the consumer stops early and the generator object is destroyed:
<?php
function readLines(string $path): Generator
{
$fh = fopen($path, 'r');
echo "opened\n";
try {
while (($line = fgets($fh)) !== false) {
yield rtrim($line);
}
} finally {
fclose($fh);
echo "closed\n";
}
}
file_put_contents('log.txt', "line 1\nline 2\nERROR here\nline 4\n");
foreach (readLines('log.txt') as $line) {
echo "read: $line\n";
if (str_starts_with($line, 'ERROR')) {
break; // generator is destroyed, finally runs
}
}
echo "done\n";
Output:
opened
read: line 1
read: line 2
read: ERROR here
closed
done
If you keep the generator in a variable, it is destroyed (and finally runs) only when the last reference goes away.
What finally does not cover
finally is skipped when the script ends without unwinding the stack:
exit()/die()- fatal errors, such as exceeding
memory_limitormax_execution_time - the process being killed (PHP-FPM
request_terminate_timeout,kill -9, a crash)
<?php
class Resource
{
public function __destruct()
{
echo "destructor runs\n";
}
}
register_shutdown_function(function (): void {
echo "shutdown function runs\n";
});
$r = new Resource();
try {
echo "in try\n";
exit(1);
} finally {
echo "finally runs\n"; // never printed
}
Output:
in try
shutdown function runs
destructor runs
On exit() shutdown functions and destructors still run, so they are the fallback for cleanup that must survive it. Things like locks held by the process and open database connections are released by the OS or the server when the process or request ends, but an unfinished transaction is rolled back, not committed. Prefer throwing an exception over calling exit() deep inside library code.
Practical cleanup patterns
Releasing a lock
<?php
function withLock(string $lockFile, callable $fn): mixed
{
$fh = fopen($lockFile, 'c');
if (!flock($fh, LOCK_EX)) {
fclose($fh);
throw new RuntimeException('could not lock');
}
try {
return $fn();
} finally {
flock($fh, LOCK_UN);
fclose($fh);
echo "lock released\n";
}
}
$total = withLock(sys_get_temp_dir() . '/report.lock', function (): int {
echo "doing exclusive work\n";
return 42;
});
echo "total: $total\n";
try {
withLock(sys_get_temp_dir() . '/report.lock', function (): never {
throw new RuntimeException('job crashed');
});
} catch (RuntimeException $e) {
echo "caught: ", $e->getMessage(), "\n";
}
Output:
doing exclusive work
lock released
total: 42
lock released
caught: job crashed
Wrapping the acquire / release pair in a function that takes a callback means callers can't forget the finally. See Locks and synchronization for more on locking.
Restoring global state
Temporarily changed global state (error handlers, ini_set() values, the current directory, locale) must be restored on every path, or the change leaks into unrelated code:
<?php
function readStrict(string $path): string
{
// Turn warnings into exceptions, but only inside this function
set_error_handler(function (int $severity, string $message): never {
throw new ErrorException($message, 0, $severity);
});
try {
return file_get_contents($path);
} finally {
restore_error_handler();
}
}
try {
readStrict('missing.txt');
} catch (ErrorException $e) {
echo "caught: ", $e->getMessage(), "\n";
}
// The global handler is back: this is a plain warning again
$result = @file_get_contents('missing.txt');
var_dump($result);
Output:
caught: file_get_contents(missing.txt): Failed to open stream: No such file or directory
bool(false)
The same shape works for the working directory:
<?php
function withDirectory(string $dir, callable $fn): mixed
{
$old = getcwd();
chdir($dir);
try {
return $fn();
} finally {
chdir($old);
}
}
mkdir('sub');
$before = basename(getcwd());
$inside = withDirectory('sub', fn() => basename(getcwd()));
$after = basename(getcwd());
echo "$before -> $inside -> $after\n";
rmdir('sub');
Output:
app -> sub -> app
Rolling back a transaction
Commit at the end of the try block, and roll back in finally if the commit didn't happen:
<?php
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('CREATE TABLE accounts (name TEXT PRIMARY KEY, balance INT CHECK (balance >= 0))');
$pdo->exec("INSERT INTO accounts VALUES ('alice', 100), ('bob', 0)");
function transfer(PDO $pdo, string $from, string $to, int $amount): void
{
$pdo->beginTransaction();
$committed = false;
try {
$stmt = $pdo->prepare('UPDATE accounts SET balance = balance + ? WHERE name = ?');
$stmt->execute([$amount, $to]);
$stmt->execute([-$amount, $from]);
$pdo->commit();
$committed = true;
} finally {
if (!$committed && $pdo->inTransaction()) {
$pdo->rollBack();
echo "rolled back\n";
}
}
}
transfer($pdo, 'alice', 'bob', 30);
try {
transfer($pdo, 'alice', 'bob', 500);
} catch (PDOException $e) {
echo "transfer failed: ", $e->getMessage(), "\n";
}
foreach ($pdo->query('SELECT name, balance FROM accounts') as $row) {
echo "{$row['name']}: {$row['balance']}\n";
}
Output:
rolled back
transfer failed: SQLSTATE[23000]: Integrity constraint violation: 19 CHECK constraint failed: balance >= 0
alice: 70
bob: 30
The $committed flag is better than catch (Throwable $e) { rollBack(); throw $e; } because it doesn't touch the exception at all. More in Database Transactions with PDO.
Several resources
Each resource gets its own try / finally, nested in the order of acquisition. Resources are then released in reverse order, and a failure to acquire the second one still releases the first:
<?php
function copyUpper(string $src, string $dst): void
{
$in = fopen($src, 'r');
if ($in === false) {
throw new RuntimeException("cannot open $src");
}
try {
$out = fopen($dst, 'w');
if ($out === false) {
throw new RuntimeException("cannot open $dst");
}
try {
while (($line = fgets($in)) !== false) {
fwrite($out, strtoupper($line));
}
} finally {
fclose($out);
echo "closed output\n";
}
} finally {
fclose($in);
echo "closed input\n";
}
}
file_put_contents('in.txt', "hello\nworld\n");
copyUpper('in.txt', 'out.txt');
echo file_get_contents('out.txt');
try {
copyUpper('in.txt', 'no/such/dir/out.txt');
} catch (RuntimeException $e) {
echo "caught: ", $e->getMessage(), "\n";
}
Output:
closed output
closed input
HELLO
WORLD
Warning: fopen(no/such/dir/out.txt): Failed to open stream: No such file or directory in /app/copy.php on line 9
closed input
caught: cannot open no/such/dir/out.txt
Destructors as an alternative: a defer helper
Deep nesting gets awkward with many resources. PHP objects are reference counted, so a local object's destructor runs as soon as the function exits, including when an exception passes through. That allows a Go-style defer:
<?php
final class Defer
{
/** @var list<Closure> */
private array $callbacks = [];
public function add(Closure $fn): void
{
$this->callbacks[] = $fn;
}
public function __destruct()
{
// Run in reverse order, like Go's defer
foreach (array_reverse($this->callbacks) as $fn) {
$fn();
}
}
}
function build(bool $fail): void
{
$defer = new Defer();
$tmp = tempnam(sys_get_temp_dir(), 'build');
$defer->add(function () use ($tmp) {
unlink($tmp);
echo " removed temp file\n";
});
$fh = fopen($tmp, 'w');
$defer->add(function () use ($fh) {
fclose($fh);
echo " closed handle\n";
});
fwrite($fh, 'partial build output');
if ($fail) {
throw new RuntimeException('compile error');
}
echo " build ok\n";
}
echo "success:\n";
build(false);
echo "failure:\n";
try {
build(true);
} catch (RuntimeException $e) {
echo " caught: ", $e->getMessage(), "\n";
}
Output:
success:
build ok
closed handle
removed temp file
failure:
closed handle
removed temp file
caught: compile error
Destructors are less explicit than finally, so use them with care:
- The cleanup runs when the last reference goes away. If the object is stored in a property, a static, a closure or a circular structure, cleanup is delayed, possibly until the garbage collector runs or the script ends.
- An exception thrown from a destructor during unwinding is chained like one thrown from
finally, and is easy to miss. - Destructors run on
exit(), whilefinallydoes not. That can be a plus.
For one or two resources, plain try / finally is clearer. See Temporary files for more on tempnam() and tmpfile().
Summary
- Acquire the resource just before
try, release it infinally. - Use
try/finallywithoutcatchwhen the function can't handle the error itself. - Never
returnfromfinally. It overrides return values and silently discards exceptions. - If cleanup can throw, catch inside
finallyso the original exception isn't replaced. - One
try/finallyper resource, nested, released in reverse order. Or wrap acquire and release in awithX(callable)helper. finallydoesn't run onexit(), fatal errors or a killed process.