Exceptions
Throw and Catch
Throwing an exception jumps to the nearest matching catch block.
Throw and Catch
throw_catch.php
<?php
$divisor = ;
try {
if ($divisor === 0) {
throw new Exception("divide by zero");
}
$result = 10 / $divisor;
$status = "ok";
} catch (Exception $error) {
$result = 0;
$status = "caught";
}
echo "divisor=" . $divisor . "\n";
echo "status=" . $status . "\n";
echo "result=" . $result . "\n";
<?php
$divisor = ;
try {
if ($divisor === 0) {
throw new Exception("divide by zero");
}
$result = 10 / $divisor;
$status = "ok";
} catch (Exception $error) {
$result = 0;
$status = "caught";
}
echo "divisor=" . $divisor . "\n";
echo "status=" . $status . "\n";
echo "result=" . $result . "\n";
<?php
$divisor = ;
try {
if ($divisor === 0) {
throw new Exception("divide by zero");
}
$result = 10 / $divisor;
$status = "ok";
} catch (Exception $error) {
$result = 0;
$status = "caught";
}
echo "divisor=" . $divisor . "\n";
echo "status=" . $status . "\n";
echo "result=" . $result . "\n";
controlled failure
A catch block turns a failure path into normal scalar state for the caller.