php · level 2 · unit 7 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
There is no orders table. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
$db = new PDO("sqlite::memory:");
try {
$db->exec("INSERT INTO orders VALUES (1)");
echo "Order saved\n";
} catch (PDOException $e) {
echo "Could not save the order\n";
}
echo "Carry on shopping\n";
your turn
Your turn. Handle a silly quantity.
Type a quantity, like 3, then run it. Then try something silly, like lots or -2, and see the friendly message.
fix it
The catch never catches. Can you fix it?
- The program still stops with an error. What kind of exception does it name?
- The database throws a
PDOException, but thecatchonly catchesInvalidArgumentException. - Change line 6 to
} catch (PDOException $e) {, then press run.
nailed it
your program keeps calm when things go wrong. :D
- Risky code goes in
try, and plan B incatch. $e->getMessage()gives the exception's message.finallyalways runs, thrown or not.
new words in your collection
- try
- catch
- finally
- getMessage
This lesson isn’t saved. A free account remembers every lesson you finish.