Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^196) CHAPTER 13 ■ SPL EXCEPTIONS
ability. If a function were to meet or exceed 10, the correct exception would be OverflowException,
to prevent a SQL error from occurring downstream, as shown in Listing 13-10.
Listing 13-10. Using OverflowException
function sumThenInsertDemo($a, $b) {
$sum = $a + $b;
if ($sum >= 10) {
throw new OverflowException("$a + $b will overflow storage");
}
$link = pg_connect(...);
pg_query($link, 'insert into test values ('. $sum .')');
}


Underflow Exceptions


An arithmetical underflow occurs when any value is too small to maintain precision and the
result of the function would result in a loss of accuracy. Underflows are handled with
UnderflowException.

class UnderflowException extends RuntimeException

You may encounter an underflow when adding floats in PHP. PHP floating-point precision
is highly dependent on the operating system, compilation settings, and processor on which
the code is running. PHP floats will not give consistent operation. However, on many systems,
it is possible to detect this underflow and write functions that are smart enough to detect it.
Listing 13-11 shows an example of arithmetic underflow in PHP floating-point operations.

Listing 13-11. Arithmetical Underflow in PHP

echo (1-0.9). "\n";
echo (1-0.99). "\n";
echo (1-0.999). "\n";
echo (1-0.9999). "\n";
echo (1-0.99999). "\n";
echo (1-0.999999). "\n";

0.1

0.01

0.001

9.9999999999989E-05

9.9999999999545E-06

1.0000000000288E-06

McArthur_819-9C13.fm Page 196 Thursday, February 28, 2008 7:53 AM

Free download pdf