php · level 2 · unit 7 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
an when something is badly wrong.
Sometimes a function is handed nonsense, like selling a ticket when none are left. Carrying on would only spread the mistake. Instead, throw an exception: throw new Exception("Sold out!");. An exception is an object that describes the problem, with your message inside.
Throwing stops the function on that line. Nothing after it runs, and the exception flies back to whoever called the function. If nothing catches it, the program stops with your message, like any other error.
PHP has ready-made kinds. is for a function handed a value it cannot use, so its name explains the problem before you read the message.
<?php
function take_ticket(int $left): int {
if ($left <= 0) {
throw new InvalidArgumentException("Sold out!");
}
return $left - 1;
}
$left = take_ticket(2);
echo "Tickets left: $left\n";
$left = take_ticket($left);
echo "Tickets left: $left\n"; Call take_ticket(0) and the program stops with InvalidArgumentException: Sold out!.
guess first
Turn it up to 11. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
function set_volume(int $level): string {
if ($level < 0 || $level > 10) {
throw new InvalidArgumentException("Volume must be 0 to 10");
}
return "Volume set to $level";
}
echo set_volume(7) . "\n";
echo set_volume(11) . "\n";
echo "Done\n";
your turn
Your turn. Raid the piggy bank.
Type an amount to spend from the £50 in the piggy bank. Try one that works, then one that is too big, and read the error.
fix it
A perfectly good age gets turned away. Fix it.
- 34 is between 0 and 120, yet the exception is thrown. When is the condition on line 3
true? - The
ifthrows for good ages. It should throw only when the age is under 0 or over 120. - Change line 3 to
if ($age < 0 || $age > 120) {, then press run.
nailed it
your functions refuse nonsense clearly. :D
throw new Exception("...")stops with your message.- Nothing after a
throwruns. InvalidArgumentExceptionmeans a bad value was handed in.
new words in your collection
- exception
- throw
- InvalidArgumentException
This lesson isn’t saved. A free account remembers every lesson you finish.