Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 13 ■ SPL EXCEPTIONS^195

This length may be the length of a string, too many or too few elements in an array, execu-
tion time limit, or even file size. Listing 13-8 shows an example of using LengthException.

Listing 13-8. Using LengthException

function printmax10($str) {
if(strlen($str) > 10) {
throw new LengthException("Input was too long");
}
echo $str;
}

printmax10('asdf');
printmax10('abcdefghijk');

asdf
Fatal error: Uncaught exception 'LengthException' with
message 'Input was too long' in listing8.php:6
Stack trace:
#0 listing8.php(12): printmax10('abcdefghijk')
#1 {main}
thrown in listing8.php on line 6

Overflow Exceptions


The PHP language will automatically handle most overflow scenarios where an integer or buffer
overflows. OverflowException is designed for arithmetical overflow scenarios or scenarios where a
value is to be stored and the result would overflow the storage location.

class OverflowException extends RuntimeException

Listing 13-9 demonstrates a common SQL scenario.

Listing 13-9. PostgreSQL Numeric Scale Overflow

postgres=# create temporary table test (demo numeric(3,2));
CREATE TABLE
postgres=# insert into test values (333.99);
postgres-# ERROR: numeric field overflow
DETAIL: The absolute value is greater than or equal to
10^2 for field with precision 3, scale 2.
postgres=# insert into test values (1.99);
postgres-# INSERT 0 1

In this example, any value over 9.99 will result in an overflow and produce an error. Thus,
any function that inserts into this table must constrain its calculations to stay within this storage

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

Free download pdf