Exceptions
Recover with Default
A catch block can choose a default value and let the program continue.
Recover with Default
recover_default.php
<?php
function parseCount(string $raw): int
{
if (!ctype_digit($raw)) {
throw new Exception("not a number");
}
return (int) $raw;
}
$raw = ;
try {
$count = parseCount($raw);
$source = "input";
} catch (Exception $error) {
$count = 0;
$source = "default";
}
echo "raw=" . $raw . "\n";
echo "count=" . $count . "\n";
echo "source=" . $source . "\n";
<?php
function parseCount(string $raw): int
{
if (!ctype_digit($raw)) {
throw new Exception("not a number");
}
return (int) $raw;
}
$raw = ;
try {
$count = parseCount($raw);
$source = "input";
} catch (Exception $error) {
$count = 0;
$source = "default";
}
echo "raw=" . $raw . "\n";
echo "count=" . $count . "\n";
echo "source=" . $source . "\n";
<?php
function parseCount(string $raw): int
{
if (!ctype_digit($raw)) {
throw new Exception("not a number");
}
return (int) $raw;
}
$raw = ;
try {
$count = parseCount($raw);
$source = "input";
} catch (Exception $error) {
$count = 0;
$source = "default";
}
echo "raw=" . $raw . "\n";
echo "count=" . $count . "\n";
echo "source=" . $source . "\n";
fallback
Recovery usually means producing a clear fallback value, not hiding the failure.