Rethrowing Exceptions
Catch an exception to log or add context, then rethrow it with throw $e or throw (bare, PHP 8+) to let callers handle it.
Catch an exception to log or add context, then rethrow it with throw $e or throw (bare, PHP 8+) to let callers handle it.
<?php
function processPayment(array $order): void {
try {
$gateway->charge($order["amount"]);
} catch (GatewayException $e) {
// Log with context before re-throwing
$this->logger->error("Payment failed for order #{$order["id"]}", [
"exception" => $e->getMessage(),
"amount" => $order["amount"],
]);
throw $e; // Rethrow — let caller decide what to do
}
}
// PHP 8: bare throw re-throws the current exception
try {
riskyOp();
} catch (Exception $e) {
cleanup();
throw; // Re-throws $e without needing the variable
}
Rethrow to maintain separation of concerns — log at one layer, handle user-facing response at another.