Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^32) CHAPTER 4 ■ EXCEPTIONS
catch
The catch block defines what to do in the case of an exception. It allows you to define the type
of exception to catch, as well as access the details of the exception that was caught. Here is
an example:
catch (Exception $e) {
echo $e;
}
In this example, $e is now an instance of the Exception class. As discussed shortly, Exception
is the highest ancestor of any type of exception, so catching Exception will catch any type of
exception.
You may define multiple catch blocks when working with different types of exceptions.
Always define the most specific type first, as catch blocks are evaluated in sequential order,
with the first block executed first.
throw
throw is used to cause an exception to occur and abort processing at that point. You must pass
an instance of Exception to throw. You can throw an exception stored in a variable or create the
instance inline.
Both of the following forms are equivalent:
$a = new Exception("Error message");
throw $a;
or
throw new Exception("Error message");
You will typically use the first form when using custom exceptions (discussed in the next
section). In these cases, you will sometimes need to set various properties of the exception
before throwing it. You can use throw with any Exception-derived class.
Exception
Exception is the base class for all exceptions. You can extend from Exception to define custom
exceptions. (Chapter 13 discusses some of the extended, built-in exceptions that are available.)
Exception’s constructor optionally takes an error message and an error code. The error
message is self-explanatory, but error codes deserve some explanation.
By providing an error code, you can later decide pragmatically what to do in the event of
an exception. By inspecting the code returned, you can numerically map exceptions without
needing to make your programming dependent on the error strings, which may be changed
from time to time. This technique is demonstrated in the “Error Coding” section later in this
chapter.
McArthur_819-9C04.fm Page 32 Friday, February 1, 2008 10:25 AM

Free download pdf