SyntaxStudy
Sign Up
PHP Intermediate 5 min read

Exception Chaining

Exception Chaining

Pass a caught exception as the third argument to a new exception to preserve the original cause. This builds a chain that helps trace root causes.

Example
<?php
function fetchUser(int $id): array {
    try {
        return $db->query("SELECT * FROM users WHERE id = ?", [$id]);
    } catch (PDOException $e) {
        // Wrap low-level DB exception in a domain exception
        throw new DataAccessException(
            "Failed to fetch user {$id}",
            500,
            $e  // $previous exception
        );
    }
}

try {
    $user = fetchUser(42);
} catch (DataAccessException $e) {
    echo $e->getMessage();         // "Failed to fetch user 42"
    echo $e->getPrevious()->getMessage(); // Original PDO error
}
Pro Tip

Always pass the original exception as the $previous argument — it preserves the full diagnostic chain for debugging.