×

php · level 3 · unit 4 · 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

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.