Separate catch blocks can handle different exception classes.

specific handler Specific exception classes let code name the kind of recovery it is doing.

Multiple Catch

mode
multiple_catch.php
Replay: real traced execution (multi-file project)
<?php
$mode = "empty";

try {
    if ($mode === "empty") {
        throw new InvalidArgumentException("missing");
    }

    if ($mode === "short") {
        throw new LengthException("short");
    }

    $status = "accepted";
} catch (InvalidArgumentException $error) {
    $status = "missing";
} catch (LengthException $error) {
    $status = "too_short";
}

echo "mode=" . $mode . "\n";
echo "status=" . $status . "\n";
<?php
$mode = "short";

try {
    if ($mode === "empty") {
        throw new InvalidArgumentException("missing");
    }

    if ($mode === "short") {
        throw new LengthException("short");
    }

    $status = "accepted";
} catch (InvalidArgumentException $error) {
    $status = "missing";
} catch (LengthException $error) {
    $status = "too_short";
}

echo "mode=" . $mode . "\n";
echo "status=" . $status . "\n";
<?php
$mode = "ready";

try {
    if ($mode === "empty") {
        throw new InvalidArgumentException("missing");
    }

    if ($mode === "short") {
        throw new LengthException("short");
    }

    $status = "accepted";
} catch (InvalidArgumentException $error) {
    $status = "missing";
} catch (LengthException $error) {
    $status = "too_short";
}

echo "mode=" . $mode . "\n";
echo "status=" . $status . "\n";
  1. $mode ← empty

    1<?php2$mode→ empty = "empty"; //@mode="short", "ready"
  2. if ($mode === "empty")

    4try {5    if ($modeempty === "empty") {6        throw new InvalidArgumentException("missing");7    }
  3. echo "mode=" . $mode . " ";

    14} catch (InvalidArgumentException $error) {15    $status = "missing";16} catch (LengthException $error) {17    $status = "too_short";18}1920echo "mode=" . $modeempty . "\n";21echo "status=" . $statusmissing . "\n";
    outputmode=empty
    status=missing
  1. $mode ← short

    1<?php2$mode→ short = "short";
  2. if ($mode === "short")

    9if ($modeshort === "short") {10    throw new LengthException("short");11}
  3. echo "mode=" . $mode . " ";

    16} catch (LengthException $error) {17    $status = "too_short";18}1920echo "mode=" . $modeshort . "\n";21echo "status=" . $statustoo_short . "\n";
    outputmode=short
    status=too_short
  1. $mode ← ready, $status ← accepted

    1<?php2$mode→ ready = "ready";34try {5    if ($mode === "empty") {6        throw new InvalidArgumentException("missing");7    }89    if ($mode === "short") {10        throw new LengthException("short");11    }1213    $status→ accepted = "accepted";14} catch (InvalidArgumentException $error) {15    $status = "missing";16} catch (LengthException $error) {17    $status = "too_short";18}1920echo "mode=" . $modeready . "\n";21echo "status=" . $statusaccepted . "\n";
    outputmode=ready
    status=accepted