Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
189

■ ■ ■


CHAPTER 13


SPL Exceptions


The SPL provides a number of built-in exception base classes that are designed to handle
everyday scenarios. In this chapter, you will learn about the base exception classes, when to
apply them, and how to extend them for your own requirements.

Logic Exceptions


The SPL has two central classes of exceptions: LogicException and RuntimeException (discussed in
the next section). The LogicException class descends from Exception directly, and does not
add any additional methods.

class LogicException extends Exception

The purpose of this classification is to allow you to differentiate between compile-time
logical exceptions and exceptions caused by bad data being passed to the application.
Invoking a logic exception is just like invoking a standard exception, except that it should
be thrown only on the condition that the application is programmed incorrectly. This type of
exception can be used to create a system for logging programming exceptions separately from
those caused by runtime data.
To get started, Listing 13-1 shows how to invoke a logic exception and a typical scenario
where you might correctly use a LogicException directly.

Listing 13-1. Throwing LogicException

class Lazy {
protected $_loaded = false;
protected $_name;

public function materialize() {
$this->_loaded = true;
$this->_name = 'Kevin';
}

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

Free download pdf