PHP › Error & Exception Handling
How does the finally block work alongside try and catch, and what are appropriate use cases for it?
IntermediateAnswer
A finally block contains code that always executes after the try and any matching catch block, regardless of whether an exception was thrown or caught, making it well suited for cleanup tasks that must always happen, such as closing a file handle or a database connection, ensuring those necessary cleanup steps run whether the preceding code succeeded, failed, or even if the code inside the catch block itself throws a new exception.
$file = fopen('data.txt', 'r');
try {
processFile($file);
} catch (Exception $e) {
logError($e);
} finally {
fclose($file);
}Real-world example A file processing function ensures the opened file handle is always closed in a finally block, guaranteeing proper resource cleanup regardless of whether the actual file processing succeeded or threw an exception partway through.