php · level 3 · unit 4 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Give your exceptions a family tree, then catch whole branches.
Big apps build an : one parent like ShopException, with children such as OutOfStock and CardDeclined. Catching the parent catches every child, so one block handles anything your shop throws, while PHP's own errors still get through.
To catch two unrelated types the same way, join them with a bar in one : catch (TooLong | Reserved $e). At the very top of PHP's tree sits , which every exception and error implements.
And finally runs last, whatever happened: success, a caught exception, even one that escapes. Use it to tidy up.
<?php
class ShopException extends Exception {}
class OutOfStock extends ShopException {}
class CardDeclined extends ShopException {}
foreach ([1200, 9900] as $pence) {
try {
if ($pence > 5000) {
throw new CardDeclined("Card declined for $pence pence.");
}
echo "Paid $pence pence.\n";
} catch (ShopException $e) {
echo get_class($e) . ": " . $e->getMessage() . "\n";
} finally {
echo "Receipt printed.\n";
}
} Catching Throwable everywhere hides real bugs, so save it for the very outside of your app.
guess first
A return and a finally. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
function load(string $file): string {
try {
if ($file === "") {
throw new InvalidArgumentException("No file name");
}
return "Loaded $file";
} finally {
echo "Closing up\n";
}
}
echo load("notes.txt") . "\n";
your turn
Your turn. Check a new username.
Type a username in the first blank: try a long one, admin, or a good one. Then catch both exception types in one block with a bar between them.
fix it
The admin page escapes the safety net. Fix it.
- The first page is caught, then an uncaught
Forbiddenstops the run. Which family doesForbiddenbelong to? catch (AppException $e)only catchesAppExceptionand its children. Look at what each class on lines 3 and 4 extends.- On line 4, make
ForbiddenextendAppException, then run it.
nailed it
you built a family tree of problems. :D
- Catching a parent exception also catches all of its children.
- Join types with
|to catch them in one block. finallyalways runs, so use it to tidy up.
new words in your collection
- exception hierarchy
- Throwable
- multi-catch
This lesson isn’t saved. A free account remembers every lesson you finish.