×

php · level 3 · unit 4 · lesson 1

  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

Name each problem with its own exception class.

Throwing a plain Exception for everything is like a shop alarm with one sound for fire, flood and burglars. A is a class that extends Exception, and its name says what went wrong: class OutOfStock extends Exception {}. The empty body is enough.

Now catch can choose problems by type. Write several catch blocks in a row. PHP tries them top to bottom and runs the first whose type fits, so put the most specific first.

Alongside the InvalidArgumentException you already know, PHP ships , for problems that only appear while the program runs.

<?php
class OutOfStock extends RuntimeException {}
function buy(string $item, int $stock): string {
    if ($stock === 0) {
        throw new OutOfStock("Sorry, $item is sold out.");
    }
    return "One $item, coming up.";
}
foreach (["scone" => 3, "eclair" => 0] as $item => $stock) {
    try {
        echo buy($item, $stock) . "\n";
    } catch (OutOfStock $e) {
        echo $e->getMessage() . "\n";
    }
}

get_class($e) gives the name of an exception's class, which helps when you debug.