Multiple Catch Blocks
Catch different exception types in separate blocks, or use | in PHP 8 to catch multiple types in one block.
Catch different exception types in separate blocks, or use | in PHP 8 to catch multiple types in one block.
<?php
try {
processPayment($order);
} catch (InvalidCardException $e) {
// Card-specific handling
return ["error" => "card_invalid", "msg" => $e->getMessage()];
} catch (InsufficientFundsException $e) {
return ["error" => "insufficient_funds", "msg" => $e->getMessage()];
} catch (NetworkException | TimeoutException $e) {
// Handle both network and timeout the same way
return ["error" => "network_error", "retry" => true];
} catch (Exception $e) {
// Catch-all for unexpected errors
error_log($e->getMessage());
return ["error" => "unexpected"];
}
Order catch blocks from most specific to least specific — put the base Exception catch last as a fallback.