Errors and Exceptions
PHP 8 throws exceptions for many errors. Wrap risky code in try and catch, use finally for clean up and throw your own exceptions. Catch the most specific type first. Throwable covers both Exception and Error.
Example
function divide(int $a, int $b): float {
if ($b === 0) throw new InvalidArgumentException("Cannot divide by zero");
return $a / $b;
}
try {
echo divide(10, 4), "\n";
echo divide(1, 0), "\n";
} catch (InvalidArgumentException $e) {
echo "Caught: ", $e->getMessage(), "\n";
} finally {
echo "Done\n";
}
try { intdiv(1, 0); } catch (DivisionByZeroError $e) { echo "Division error\n"; }Result
2.5 Caught: Cannot divide by zero Done Division error
Exercise
Raise an exception.
new Exception("oops");Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.