Codectionary / Developer documentation / PHP

Preserve Error Causes with Exception Chaining

Wrap a low-level failure in an application-level exception while retaining its original cause.

What it is and why to use it

An import service may want to report “Import failed” while retaining the parsing failure that caused it. Exception chaining connects those two levels. Pass the original Throwable as the third constructor argument of a new exception. The caller can handle the higher-level failure, and controlled diagnostic code can still inspect the earlier cause.

How it works

Catch the specific exception you intend to translate, then throw a new exception with a message, integer code and previous Throwable. getPrevious() retrieves that cause or returns null when none exists. Wrapping does not automatically log anything or make an error message safe. At a public boundary, return a stable user-facing message and keep any necessary diagnostics redacted and access-controlled.

Common mistakes and limitations

Do not catch every failure only to discard it or expose its raw message publicly. Exception messages and traces can contain file paths, query details or sensitive values. Do not return success after a failed operation. Preserve the cause only when translation adds useful context rather than layers of identical exceptions.

Run the examples locally

Save each complete example in its own example.php file and run php example.php in a terminal from that folder. Each example is independent: do not paste both into one file, especially when they declare classes with the same names. Output appears in the terminal. The examples use PHP 8.0-compatible syntax; use a currently supported PHP release for development.

The <?php opening tag starts PHP code. declare(strict_types=1) requests strict scalar argument checks for function calls made from this file; it does not validate external input for you. echo writes output, and PHP_EOL adds the platform’s line ending. Quotation marks delimit strings; they are not part of the printed text unless explicitly included in the string.

These examples use built-in PHP language features and standard extensions. They need no Composer packages, database server, browser APIs or network access. Codectionary’s PHP preview does not execute PHP; use your local interpreter to reproduce the output.

Check your interpreter, lint and run one saved example

php -v
php -l example.php
php example.php

Continue learning

Use the related guides to connect this operation to the surrounding language features. Practise by changing the example inputs and predicting the output before running it.

Syntax

throw new RuntimeException('Import failed', 0, $cause);

Examples

Wrap a parser failure and keep the cause

Use fixed demonstration messages to inspect a two-level chain in a local terminal.

<?php
declare(strict_types=1);

function readScore(string $text): int {
    if (!ctype_digit($text)) {
        throw new InvalidArgumentException('Expected decimal digits');
    }
    return (int) $text;
}
function importScore(string $text): int {
    try {
        return readScore($text);
    } catch (InvalidArgumentException $cause) {
        throw new RuntimeException('Import failed', 0, $cause);
    }
}
try {
    importScore('unknown');
} catch (RuntimeException $error) {
    echo $error->getMessage(), PHP_EOL;
    echo get_class($error->getPrevious()), PHP_EOL;
}
  1. The small parser accepts only digit strings for this demonstration; the invalid sample triggers InvalidArgumentException.
  2. importScore catches that specific failure and passes it into the new RuntimeException as its previous cause.
  3. The local catch prints a generic summary and the cause’s class, not raw sensitive data. A production score parser would also validate numeric range before casting.
  4. Expected output: Import failed InvalidArgumentException

Handle an exception without a previous cause

Check for null instead of assuming every exception wraps another one.

<?php
declare(strict_types=1);

$error = new RuntimeException('No earlier cause');
$previous = $error->getPrevious();
echo $previous === null ? 'No chained exception' : get_class($previous), PHP_EOL;
  1. The constructor receives no third argument, so there is no previous Throwable.
  2. getPrevious returns null rather than an empty exception object.
  3. A diagnostic chain walker must stop at null. Never call a cause’s methods without checking that a cause exists.
  4. Expected output: No chained exception

Best practices

  • Translate failures at meaningful abstraction boundaries.
  • Keep detailed exception chains out of public responses.

Runtime & versions

PHP runtime on a server or CLI. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

PHP Manual

Specifications & further reading