finally
The "finally" keyword is a feature of exception handling in PHP that allows you to specify code that will be executed regardless of whether an exception was
The PHP "finally" Keyword: A Comprehensive Guide
The finally keyword is part of PHP's exception-handling syntax. A finally block is attached to a try statement and is guaranteed to run after the try block (and any matching catch block) — whether the code succeeded, threw an Exception, or returned early. That guarantee makes it the right place for cleanup work: closing files, releasing locks, ending database transactions, or logging.
This page covers the syntax, the exact order in which the blocks run, how finally interacts with return, and the common patterns where you actually need it.
Syntax
The finally block is attached to a try statement and executes after the try and any catch blocks, regardless of whether an exception was thrown or handled. Here is the basic syntax for using the finally keyword in PHP:
The PHP syntax of finally
try {
// code to be executed
} catch (Exception $e) {
// code to handle the exception
} finally {
// code to be executed regardless of whether an exception was thrown or caught
}The catch block is optional when a finally block is present — try ... finally (with no catch) is valid PHP. In that case the finally block still runs, but any exception is left uncaught and propagates up after finally finishes.
How the blocks run
The order is always the same:
- The
tryblock runs. - If an exception is thrown, the first matching
catchblock runs. If none matches, the exception is held to be re-thrown. - The
finallyblock runs — always. - Control leaves the statement (returning a value, or re-throwing an uncaught exception).
This small script makes the order visible:
<?php
function demo(bool $fail): void
{
try {
echo "1. try\n";
if ($fail) {
throw new Exception("boom");
}
} catch (Exception $e) {
echo "2. catch: {$e->getMessage()}\n";
} finally {
echo "3. finally\n";
}
echo "4. after\n";
}
demo(false);
echo "---\n";
demo(true);
// Output:
// 1. try
// 3. finally
// 4. after
// ---
// 1. try
// 2. catch: boom
// 3. finally
// 4. afterNotice that finally runs in both cases — once with no exception, once after the catch.
Examples
Let's look at some practical examples of how the finally keyword can be used:
Examples of PHP finally
<?php
// Example 1
function divide($a, $b)
{
try {
if ($b == 0) {
throw new Exception("Division by zero.");
}
return $a / $b;
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
} finally {
echo "This code will always be executed.";
}
}
divide(10, 0);
// Output: Error: Division by zero.This code will always be executed.
// Example 2
$file = "example.txt";
$handle = fopen($file, "r");
try {
if (!$handle) {
throw new Exception("Unable to open file.");
}
// code to be executed
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
} finally {
if ($handle !== false) {
fclose($handle);
}
}
// Output: Error: Unable to open file.In these examples, we use the finally keyword to ensure cleanup or logging code runs consistently.
finally and return
A finally block runs even when try or catch contains a return. PHP evaluates the return value, then runs finally, then actually returns. If the finally block itself returns a value, that value overrides the earlier one — a subtle source of bugs, so avoid returning from finally.
<?php
function withReturn(): string
{
try {
return "from try";
} finally {
echo "finally still runs\n";
}
}
function overriding(): string
{
try {
return "from try";
} finally {
return "from finally"; // overrides the try return
}
}
echo withReturn() . "\n";
echo overriding() . "\n";
// Output:
// finally still runs
// from try
// from finallyThe same overriding rule applies to exceptions: if finally throws, its exception replaces any exception or return value that was pending from try/catch.
Benefits
Using the finally keyword has several benefits, including:
- Improved error handling: Ensures that essential cleanup or logging code runs consistently, even when exceptions occur or are handled.
- Simplified code: Eliminates the need to duplicate resource-closing logic across multiple
catchblocks or error paths.
Conclusion
In summary, the finally keyword provides a reliable way to execute essential cleanup code during exception handling — closing resources, releasing locks, and logging — regardless of whether an exception was thrown. Use it whenever a resource opened in try must be released no matter what, and avoid return-ing from a finally block so you don't accidentally swallow a result or exception.
To go deeper into PHP error handling, see try, catch, the Exception class, and the broader guide to PHP exceptions.