×

php · level 2 · unit 7 · lesson 3

  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

and turn a crash into a plan B.

An exception does not have to end your program. Put the risky code in a try block. If anything inside throws, PHP jumps straight to the catch block, then carries on after it.

catch (InvalidArgumentException $e) names the kind it catches and puts the exception in $e. hands back its message, ready to show the visitor. Catch the kind you expect, such as PDOException for database trouble, so surprises still show up.

A block after them always runs, thrown or not. It suits tidying up, like a closing message.

<?php
function check_age(int $age): int {
    if ($age < 0) { throw new InvalidArgumentException("Age cannot be negative"); }
    return $age;
}
try {
    echo "Age: " . check_age(-3) . "\n";
} catch (InvalidArgumentException $e) {
    echo "Sorry: " . $e->getMessage() . "\n";
} finally {
    echo "Thanks for visiting\n";
}

Nothing in the try after the throw runs, not even the rest of that line.