Catching Errors
PHP raises an Error when code breaks a rule of the engine itself, like passing an array where a number is required. A catch block can catch an Error, so the program can carry on instead of stopping.
A TypeError caught instead of stopping the program
The function asks for an int, and the call passes an array instead. Earlier lessons let this failure stop the program. Here the catch block handles it and prints the class name of the error.
<?php
function showNumber(int $n) {
echo $n, "\n";
}
try {
showNumber([1, 2]);
} catch (TypeError $e) {
echo get_class($e), " caught\n";
}One catch block handles two error types
The pipe in the catch line lists both types. Each try block raises one of them, and the same catch shape prints each class name.
<?php
function printAge(int $age) {
echo $age, "\n";
}
try {
printAge([18]);
} catch (TypeError | DivisionByZeroError $e) {
echo get_class($e), "\n";
}
try {
$share = intdiv(10, 0);
echo $share, "\n";
} catch (TypeError | DivisionByZeroError $e) {
echo get_class($e), "\n";
}Catching Error catches a call on null
A method call on null raises an Error. Catching the base Error class catches it.
<?php
$reader = null;
try {
$reader->greet();
} catch (Error $e) {
echo get_class($e), " caught\n";
}Example
<?php
function divide(int $a, int $b) {
return intdiv($a, $b);
}
try {
echo divide(10, 0), "\n";
} catch (TypeError | DivisionByZeroError $e) {
echo get_class($e), " caught\n";
}
try {
echo divide([10], 2), "\n";
} catch (TypeError | DivisionByZeroError $e) {
echo get_class($e), " caught\n";
}
try {
$helper = null;
$helper->divide();
} catch (Error $e) {
echo get_class($e), " caught\n";
}
echo "Program finished\n";Key points
- A TypeError is an Error raised when a value has the wrong type for its job.
- DivisionByZeroError is an Error raised when a division tries to divide by zero.
- get_class gives the class name of an object as text.
- A multi-catch lists two or more types with a pipe between them, and one block handles any of them.
- Error is the base class for engine errors, so catching Error catches any of them.
In this example, divide shares a number with intdiv. The first call divides by zero, and the multi-catch prints DivisionByZeroError caught. The second call passes an array, and the same catch shape prints TypeError caught. The third try calls a method on null, and the base Error catch prints Error caught. The last line shows the program reached its end.
Note
A catch block for Exception does not catch an Error, because the two families are separate.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A catch line lists TypeError | DivisionByZeroError. Which errors can that one block catch?