Skip to content

ArithmeticError

The error a calculation raises when it has no right answer.

Dividing by zero is the usual way to meet it. So is a remainder by zero, and a total too large for the whole-number type it was going to be kept in. The calculation stops, so a wrong figure never reaches a page, a database row or an invoice.

Catching it by name handles the one case a program expects — an empty basket, a missing baseline — and leaves every other kind of failure alone. The message it carries names the operation that gave up.

Good to know: it sits directly under Throwable rather than under RuntimeError, so a clause written to catch runtime errors does not catch this one.

The examples below show a division by a count that turns out to be zero, a total too large to hold, and a report that names the rows it could not work out and finishes anyway.

Examples

A count that turns out to be zero

<?nvs
// Dividing by a count that came from somewhere else is the everyday way to meet
// this error: one of the baskets below is empty. Novis refuses that division
// rather than answering infinity, so the empty basket has to be handled.
array<int> $baskets = [3, 0, 5];
foreach ($baskets as int $items) {
try {
float $each = 1200 / $items;
echo $items, ' items: ', $each, " cents each\n";
} catch (ArithmeticError $noAnswer) {
echo $items, ' items: ', $noAnswer->message, "\n";
}
}
Output
3 items: 400 cents each
0 items: Division by zero
5 items: 240 cents each

A total too large to hold

<?nvs
// A whole number that is too large throws an `ArithmeticError`. It never wraps
// around to a small or negative number. The message names the operation that
// failed: here it is "Integer multiplication overflowed".
int $bytesPerRow = 4000000000;
array<int> $rowCounts = [2, 3000000000];
foreach ($rowCounts as int $rows) {
try {
int $total = $bytesPerRow * $rows;
echo $rows, ' rows: ', $total, " bytes\n";
} catch (ArithmeticError $tooLarge) {
echo $rows, ' rows: ', $tooLarge->message, "\n";
}
}
Output
2 rows: 8000000000 bytes
3000000000 rows: Integer multiplication overflowed

A dashboard row with no baseline

<?nvs
// This dashboard calculates each row on its own. A product that sold nothing last
// month makes the division by zero throw an `ArithmeticError`. That row prints
// `new`, and the other rows still print their growth.
final class Growth
{
public static function since(int $before, int $now): string
{
try {
float $percent = ($now - $before) * 100 / $before;
return ($percent as string) . '%';
} catch (ArithmeticError $noBaseline) {
return 'new';
}
}
}
array<string> $products = ['notebook', 'pencil case', 'eraser'];
array<int> $lastMonth = [120, 0, 40];
array<int> $thisMonth = [180, 90, 0];
int $row = 0;
while ($row < 3) {
echo $products[$row], ': ', Growth::since($lastMonth[$row], $thisMonth[$row]), "\n";
$row = $row + 1;
}
Output
notebook: 50%
pencil case: new
eraser: -100%