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"; }}3 items: 400 cents each0 items: Division by zero5 items: 240 cents eachA 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"; }}2 rows: 8000000000 bytes3000000000 rows: Integer multiplication overflowedA 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;}notebook: 50%pencil case: neweraser: -100%