PHP, lesson 9
When something goes wrong at run time, modern PHP throws an object describing the problem. If nothing catches it, the script stops with a "Fatal error: Uncaught …" message. Catching lets your program recover, report the problem nicely, or try something else.
When a statement inside try throws, PHP jumps straight to the first catch block whose type
matches. The variable ($e) holds the thrown object; getMessage() returns its text. Since PHP
8 you can leave the variable out when you don't need it: catch (DivisionByZeroError).
Everything you can throw implements the Throwable interface, which has two main branches:
2 exercises to try what you just read.
ExceptionInvalidArgumentExceptionRuntimeExceptionLengthExceptionError: usually a bug in the code, raised by PHP itself. Subclasses include TypeError
(wrong argument type), ValueError (right type, impossible value), DivisionByZeroError
and UnhandledMatchError.catch (Exception $e) does not catch an Error, and vice versa. catch (Throwable $e)
catches both, which is useful at the very top of a program but too broad elsewhere.
The | lets one block handle several unrelated types. finally runs whether or not anything
was thrown, so it's the place for clean-up code.
When your own function gets something it can't handle, throw:
Since PHP 8, throw is an expression, so it also works in places like ?? and arrow
functions: $name = $input ?? throw new InvalidArgumentException("name required");.
Define a class that extends Exception (or one of its subclasses) when a failure belongs to
your program's own rules. An empty body is enough; the class name carries the meaning:
Callers can now catch exactly OutOfStockException and let anything unexpected through.
Casting with (int) or (float) never fails, it silently gives 0 for garbage. To reject
bad input, check it first with is_numeric(), which accepts strings like "42", "-3.5" and
"1e3", and refuses "abc" or "".
Some older functions report problems with a warning instead of throwing, for example
reading a missing array key. Warnings print a message and carry on. Avoid them by checking
first (isset(), ??), rather than trying to catch them.
Each input line holds two values separated by a space. Divide the first by the second and print the result with two decimals. Instead of crashing:
error: not a numbererror: division by zeroWrite divide(string $a, string $b): float, which throws an InvalidArgumentException for
non-numeric input and lets PHP's own DivisionByZeroError happen for zero. Catch both in the
loop.
Sample input:
Sample output:
The first line is the starting balance (a whole number). Each following line is
deposit N or withdraw N. Define InsufficientFundsException (extending
RuntimeException) and make withdraw(int $balance, int $amount): int throw it when the
amount is larger than the balance. When a withdrawal fails, print declined: balance is B and
carry on. At the end print final: B.
Sample input:
Sample output:
<?php
try {
$result = intdiv(10, 0);
echo $result, "\n"; // skipped: the line above threw
} catch (DivisionByZeroError $e) {
echo "Oops: ", $e->getMessage(), "\n"; // Oops: Division by zero
}
echo "Still running\n";<?php
try {
$value = parse($input);
} catch (InvalidArgumentException | LengthException $e) {
echo "Bad input: ", $e->getMessage(), "\n";
} catch (RuntimeException $e) {
echo "Could not process\n";
} finally {
echo "Done\n"; // always runs, error or not
}<?php
function setVolume(int $level): int
{
if ($level < 0 || $level > 10) {
throw new InvalidArgumentException("volume must be 0-10, got $level");
}
return $level;
}<?php
class OutOfStockException extends RuntimeException {}
function take(int $stock, int $amount): int
{
if ($amount > $stock) {
throw new OutOfStockException("only $stock left");
}
return $stock - $amount;
}10 4
7 0
abc 22.50
error: division by zero
error: not a number50
withdraw 20
withdraw 40
deposit 15declined: balance is 30
final: 45