php · level 3 · unit 4 · lesson 1
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Two catch blocks could fit. Which one runs?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
class OutOfStock extends RuntimeException {}
try {
throw new OutOfStock("No more crumpets");
} catch (RuntimeException $e) {
echo "Something went wrong: " . get_class($e) . "\n";
} catch (OutOfStock $e) {
echo "Sold out: " . $e->getMessage() . "\n";
}
your turn
Your turn. Refuse impossible ages.
Name your exception, like BadAge, and type that name in both of the first two blanks. Then try any age, sensible or silly, in the last one.
fix it
The order form crashes instead of explaining. Fix it.
- The run stops with an uncaught
InvalidArgumentException. There is acatch, so why does it not step in? - A
catchonly catches its own type and that type's children. AnInvalidArgumentExceptionis not anOutOfStock. - On line 11, change
OutOfStocktoInvalidArgumentException, then run it.
nailed it
you gave every problem its own name. :D
- A custom exception is a class that extends
Exception. catchblocks are tried in order, so put specific types first.- PHP ships
InvalidArgumentExceptionandRuntimeException, ready to extend.
new words in your collection
- custom exception
- RuntimeException
This lesson isn’t saved. A free account remembers every lesson you finish.