SyntaxStudy
Sign Up
PHP try, catch, finally Blocks
PHP Intermediate 5 min read

try, catch, finally Blocks

try/catch/finally

The try block contains risky code. catch handles specific exceptions. finally always runs — even if an exception was thrown and not caught.

Example
<?php
$connection = null;

try {
    $connection = openDatabase();
    $data = fetchData($connection);
    processData($data);
} catch (DatabaseException $e) {
    error_log("DB error: " . $e->getMessage());
    throw $e; // Re-throw after logging
} catch (Exception $e) {
    error_log("Unexpected: " . $e->getMessage());
} finally {
    // Close connection even if exception was thrown
    if ($connection) {
        $connection->close();
    }
}
Pro Tip

finally is perfect for cleanup (closing files, connections, releasing locks) — it runs regardless of the outcome.