SyntaxStudy
Sign Up
PHP Multiple and Union Catch Blocks
PHP Intermediate 4 min read

Multiple and Union Catch Blocks

Multiple Catch Blocks

Catch different exception types in separate blocks, or use | in PHP 8 to catch multiple types in one block.

Example
<?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"];
}
Pro Tip

Order catch blocks from most specific to least specific — put the base Exception catch last as a fallback.