Engine Errors
Engine errors are the errors that PHP itself raises when a call receives a bad value. ValueError is the engine error for a value outside the range an argument allows.
A ValueError caught and printed
The str_repeat call asks for a negative repeat count. The ValueError catch prints the class name and the message, with no file path.
<?php
try {
echo str_repeat("ab", -1), "\n";
} catch (ValueError $e) {
echo get_class($e) . ": " . $e->getMessage() . "\n";
}The same call left uncaught
This file has no try block around the same call. The program stops, and the output holds the fatal error line.
<?php
echo str_repeat("ab", -1), "\n";A TypeError and a ValueError in turn
The first call passes an array where a string belongs and raises a TypeError. The second call raises a ValueError, and each catch prints its own line.
<?php
try {
echo strlen([]), "\n";
} catch (TypeError $e) {
echo get_class($e) . ": " . $e->getMessage() . "\n";
}
try {
echo str_repeat("ab", -1), "\n";
} catch (ValueError $e) {
echo get_class($e) . ": " . $e->getMessage() . "\n";
}Two division forms, one error class
The intdiv call and the modulo line both divide by zero. Both catches name DivisionByZeroError, and the messages keep the two forms apart.
<?php
try {
$x = intdiv(1, 0);
} catch (DivisionByZeroError $e) {
echo get_class($e) . ": " . $e->getMessage() . "\n";
}
try {
$y = 1 % 0;
} catch (DivisionByZeroError $e) {
echo get_class($e) . ": " . $e->getMessage() . "\n";
}Example
<?php
try {
echo str_repeat("ab", -1), "\n";
} catch (ValueError $e) {
echo "Repeat: " . get_class($e) . "\n";
}
try {
$x = intdiv(1, 0);
} catch (DivisionByZeroError $e) {
echo "Divide: " . get_class($e) . "\n";
}
try {
echo strlen([]), "\n";
} catch (TypeError $e) {
echo "Length: " . get_class($e) . "\n";
}
echo "Validator finished\n";Key points
- ValueError reports a value outside the allowed range for an argument.
- str_repeat raises a ValueError when the repeat count is negative.
- An uncaught ValueError stops the program with a fatal error line.
- Separate catch blocks can handle a TypeError and a ValueError in turn.
- intdiv by zero and a modulo by zero both throw DivisionByZeroError.
- The intdiv message says Division by zero and the modulo message says Modulo by zero.
In this example, a small validator makes three bad calls in a row. Each call fails with a different engine error, and each catch prints one verdict line. The final line proves the program survived all three failures.
Note
A caught engine error prints no file path when the program prints only its class and message.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does str_repeat raise when the repeat count is negative?