PHP Exceptions
Exceptions represent exceptional conditions that disrupt normal program flow. PHP uses try/catch/finally blocks to handle them gracefully.
Exceptions represent exceptional conditions that disrupt normal program flow. PHP uses try/catch/finally blocks to handle them gracefully.
<?php
try {
$result = divide(10, 0);
echo $result;
} catch (DivisionByZeroError $e) {
echo "Cannot divide by zero: " . $e->getMessage();
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
} finally {
echo "This always runs";
}
function divide(int $a, int $b): float {
if ($b === 0) throw new DivisionByZeroError("Division by zero");
return $a / $b;
}
Catch the most specific exception types first — PHP matches the first catch block whose type fits the thrown exception.