×

php · level 2 · unit 7 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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!.