Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^192) CHAPTER 13 ■ SPL EXCEPTIONS
} else {
//Abort transaction
throw new RuntimeException("The account has insufficient funds.");
}
}


Bad Function and Method Call Exceptions


BadFunctionCallException is designed to be thrown when a function call was illegal.

class BadFunctionCallException extends LogicException

This can occur in several scenarios. One of the more common is where too many parameters
are passed to a function that accepts a variable number of arguments.
BadMethodCallException is the same as BadFunctionCallException, but is designed for use
from a method context.

class BadMethodCallException extends BadFunctionCallException

Domain Exceptions


The DomainException class is designed to handle domain exceptions.

class DomainException extends LogicException

This calls for a bit of a math lesson. In researching this chapter, I found that many PHP
programmers do not know what a domain is in a mathematical sense; in fact, I was one of them.
There are a lot of really complicated math-lingo explanations for what a domain is, but
they involve a bunch of characters I can’t find on my keyboard. The simple explanation is this:
a domain is all the possible values for a function that will result in valid output from the function.
Listing 13-4 shows an example.

Listing 13-4. A Domain Function

function mathy($x) {
if($x==2) {
throw new DomainException("X cannot be 2");
}
return (1 / ($x - 2));
}

In this case, the domain is any number that is not 2, because an input of 2 would result
in a division-by-zero error. Thus, 2 is not in the domain of this function because it would result
in an error.
What this means for you, as a programmer, is that any time you have a function that takes
a certain valid set of values and you are provided with something invalid, you are supposed to
throw a DomainException exception.
In my research, I found that this is commonly confused with the RangeException exception.

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

Free download pdf