Challenge 2 — Solution
Task: Create a custom exception InvalidAgeException extending
Exception. Write a function setAge($age) that throws it if age is below
0 or above 130, otherwise echoes "Age set to $age." Test it with a
try/catch/finally, where the finally block always echoes "Validation
attempt complete."
130) {
throw new InvalidAgeException("$age is not a valid age.");
}
echo "Age set to $age.
";
}
try {
setAge(200);
} catch (InvalidAgeException $e) {
echo "Invalid age: " . $e->getMessage() . "
";
} finally {
echo "Validation attempt complete.";
}
?>
Output:
Invalid age: 200 is not a valid age.
Validation attempt complete.
Notes:
- InvalidAgeException extends the built-in Exception with an empty body
- it inherits everything Exception already provides (including
getMessage()) purely through inheritance, needing no extra code of
its own.
- setAge(200) throws immediately since 200 is above the 130 upper
bound, so the "Age set to..." success line inside setAge() never
runs at all.
- "Validation attempt complete." prints regardless of whether setAge()
succeeded or threw - if setAge(45) had been called instead, the
catch block would be skipped entirely, but finally would still run
and print the identical closing line.