Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
31

■ ■ ■


CHAPTER 4


Exceptions


Introduced in PHP 5, exceptions are a critical part of any OOP application. The term exception
refers to the entire machinery of try, catch, and throw statements, and the Exception class. This
machinery is designed to help you define when a problem occurs and what the code should do
when a problem is encountered.
Exceptions give you control over how your program generates and handles errors. Exceptions
also make your programming life easier by providing details about the context of the exception.
By using exceptions, you will be able to create more robust applications that are fault-tolerant
and that can inform an administrator when problems arise.
In this chapter, I will show you how to use built-in exceptions, as well as how to extend
exceptions in your own applications.

Implementing Exceptions


An exception should be used for any type of error that is not supposed to occur in normal code
execution. For example, you might implement an exception in a section of code that connects
to an external database, to handle the possibility of a database connection failure.

Exception Elements


Exceptions are implemented by the addition of three keywords: try, catch, and throw, as well
as the creation of the built-in Exception base class. These language constructs allow you to run
error-prone sections of code and recover from failure.

try
The try keyword is used to define a block of code in which to watch for exceptions. You use the
try block with braces, just as you would use any other block statement, such as if, while, or
for. A try block has the following form:

try {
//Code
}

The code within this block will be run until it completes or an exception is thrown. If an
exception is thrown, the rest of the code is skipped, and execution resumes at the catch block.

McArthur_819-9C04.fm Page 31 Friday, February 1, 2008 10:25 AM

Free download pdf