Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^194) CHAPTER 13 ■ SPL EXCEPTIONS
Fatal error: Uncaught exception 'RangeException' with message
'The sensor broke down.' in listing6.php:14
Stack trace:
#0 listing6.php(19): Monitor::watch()
#1 {main}
thrown in listing6.php on line 14


Invalid Argument Exceptions


The InvalidArgumentException exception is designed to be thrown when a function or method
receives an argument that is invalid.

class InvalidArgumentException extends LogicException

This is distinct from a DomainException in that it does not deal with a set of values, but
instead involves the mixing of incompatible types. For example, when calling a function that
expects an integer, passing a string might be considered an invalid argument. Listing 13-7
demonstrates using InvalidArgumentException.

Listing 13-7. Using InvalidArgumentException

function sum($a, $b) {
if(!is_numeric($a) || !is_numeric($b)) {
throw new InvalidArgumentException("Invalid Argument");
}
return ($a+$b);
}

echo sum(1,2);
echo sum('a','b');

3

Fatal error: Uncaught exception 'InvalidArgumentException'
with message 'Invalid Argument' in listing7.php:6
Stack trace:
#0 listing7.php(12): sum('a', 'b')
#1 {main}
thrown in listing7.php on line 6

Length Exceptions


LengthException should be thrown whenever a problem with length occurs.

class LengthException extends LogicException

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

Free download pdf