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.
The try block contains risky code. catch handles specific exceptions. finally always runs — even if an exception was thrown and not caught.
<?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();
}
}
finally is perfect for cleanup (closing files, connections, releasing locks) — it runs regardless of the outcome.