- Handling errors using try-catch blocks.
<?php
function divide($numerator, $denominator) {
if ($denominator == 0) {
throw new Exception("Division by zero.");
}
return $numerator / $denominator;
}
try {
echo divide(10, 2); // Output: 5
echo divide(10, 0); // This will throw an exception
} catch(Exception $e) {
echo "Error: " . $e->getMessage();
}
?>
Leave a Reply