<?php
// try/catch
try {
$result = 10 / 2;
echo "10 / 2 = $result
";
// This would throw
// $result = 10 / 0;
} catch (DivisionByZeroError $e) {
echo "❌ " . $e->getMessage() . "
";
}
// Custom exception
function validateAge(int $age): void {
if ($age < 0) throw new InvalidArgumentException("Age cannot be negative");
if ($age > 150) throw new RangeException("Age too high");
echo "✅ Valid age: $age
";
}
try {
validateAge(25);
validateAge(-5);
} catch (InvalidArgumentException $e) {
echo "❌ Invalid: " . $e->getMessage() . "
";
} catch (RangeException $e) {
echo "❌ Range: " . $e->getMessage() . "
";
} finally {
echo "
(finally always runs)";
}
?>