A custom exception class gives a domain-specific name to a failure.

domain error The class name can be more useful than a generic message when selecting recovery.

Custom Exception

count
custom_exception.php
Replay: real traced execution (multi-file project)
<?php
class LimitExceeded extends Exception
{
}

$count = 4;

try {
    if ($count > 5) {
        throw new LimitExceeded("too many");
    }

    $status = "within_limit";
} catch (LimitExceeded $error) {
    $status = "limit_error";
}

echo "count=" . $count . "\n";
echo "status=" . $status . "\n";
<?php
class LimitExceeded extends Exception
{
}

$count = 2;

try {
    if ($count > 5) {
        throw new LimitExceeded("too many");
    }

    $status = "within_limit";
} catch (LimitExceeded $error) {
    $status = "limit_error";
}

echo "count=" . $count . "\n";
echo "status=" . $status . "\n";
<?php
class LimitExceeded extends Exception
{
}

$count = 8;

try {
    if ($count > 5) {
        throw new LimitExceeded("too many");
    }

    $status = "within_limit";
} catch (LimitExceeded $error) {
    $status = "limit_error";
}

echo "count=" . $count . "\n";
echo "status=" . $status . "\n";
  1. $count ← 4, $status ← within_limit

    6$count→ 4 = 4; //@count=2, 878try {9    if ($count > 5) {10        throw new LimitExceeded("too many");11    }1213    $status→ within_limit = "within_limit";14} catch (LimitExceeded $error) {15    $status = "limit_error";16}1718echo "count=" . $count4 . "\n";19echo "status=" . $statuswithin_limit . "\n";
    outputcount=4
    status=within_limit
  1. $count ← 2, $status ← within_limit

    6$count→ 2 = 2;78try {9    if ($count > 5) {10        throw new LimitExceeded("too many");11    }1213    $status→ within_limit = "within_limit";14} catch (LimitExceeded $error) {15    $status = "limit_error";16}1718echo "count=" . $count2 . "\n";19echo "status=" . $statuswithin_limit . "\n";
    outputcount=2
    status=within_limit
  1. $count ← 8

    6$count→ 8 = 8;
  2. if ($count > 5)

    8try {9    if ($count8 > 5) {10        throw new LimitExceeded("too many");11    }
  3. echo "count=" . $count . " ";

    14} catch (LimitExceeded $error) {15    $status = "limit_error";16}1718echo "count=" . $count8 . "\n";19echo "status=" . $statuslimit_error . "\n";
    outputcount=8
    status=limit_error