Back to results for “Exception Handling”
PHP › Error & Exception Handling

What is exception chaining in PHP, and how does the previous exception parameter help preserve the original context when re throwing an error?

Intermediate

Answer

Exception chaining lets you pass an original exception as the previous parameter when constructing and throwing a new exception, preserving the full chain of what actually caused the error even as it gets wrapped in higher level, more descriptive exception types as it propagates up through different layers of your application, which is extremely valuable for debugging since you can trace the exact root cause rather than only seeing the final, more generic exception message.
try {
    $pdo->query($sql);
} catch (PDOException $e) {
    throw new DatabaseException('Failed to fetch user data', previous: $e);
}
Real-world example A developer investigating a reported bug traces a high level DatabaseException all the way back to its original underlying PDOException using the exception chain, immediately identifying the specific SQL error that ultimately caused the problem.

Common follow-ups: How do you access the previous exception from within a catch block?;Does exception chaining affect the stack trace shown when logging an error?