Pro PHP- Patterns, Frameworks, Testing and More

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

Range Exceptions


The RangeException class is designed to handle range exceptions.

class RangeException extends RuntimeException

Like the domain, the range of a function is a math term. Contrary to popular belief, it
doesn’t mean the valid range of any input for a function. For example, the code in Listing 13-5
is semantically incorrect.

Listing 13-5. Improper Use of RangeException

function mathy($x) {
if ($x < 0) {
throw new RangeException('$x must be 0 or greater');
}
}

The range of a function has nothing to do with the inputs. Instead, that is the domain of
the function and should be handled with DomainException.
The range of a function is the set of all possible values for its result—its output. So,
RangeException is for throwing exceptions regarding the result of a function.
To understand where you might use RangeException, think of a temperature sensor. Its
valid range when interfaced will be to return a value between –50 and +50 Celsius. If it starts
returning a value outside this range, you know your sensor broke.
RangeException is a runtime exception, rather than a logical exception like DomainException,
because it refers to result data. Listing 13-6 shows the proper use of RangeException.

Listing 13-6. Proper Use of RangeException

class Sensor {
public static function getTemperature() {
return 51;
}
}

class Monitor {
public static function watch() {
$temp = Sensor::getTemperature();
if(($temp < -50) || ($temp > 50)) {
throw new RangeException('The sensor broke down.');
}
}
}

Monitor::watch();

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

Free download pdf