Chapter 7 Exception Handling
catch (fileOpenException $foe)
echo ‘<p><strong>Orders file could not be opened. ‘
.’Please contact our webmaster for help.</strong></p>’;
catch (Exception $e)
echo ‘<p><strong>Your order could not be processed at this time. ‘
.’Please try again later.</strong></p>’;
You can see that the file I/O section of the script is wrapped in a
block.It is gener-
ally considered good coding practice to have small
blocks and catch the relevant
exceptions at the end of each.This makes your exception handling code easier to write
and maintain because you can see what you are dealing with.
If you cannot open the file,you throw a
;if you cannot lock the
file,you throw a
;and if you cannot write to the file,you throw a
Look at the
blocks.To illustrate a point, we have included only two:one to
s and one to handle
s. Because the other excep-
tions inherit from
,they will be caught by the second
blocks are matched on the same basis as the
operator.This is a good reason
for extending your own exception classes from a single class.
One important warning:If you raise an exception for which you have not written a
matching catch block,PHP will report a fatal error.
Exceptions and PHP’s Other Error Handling
In addition to the exception handling mechanism discussed in this chapter, PHP has
complex error handling support,which we consider in Chapter 25,“Debugging.”Note
that the process of raising and handling exceptions does not interfere or prevent this
error handling mechanism from operating.
In Listing 7.5,notice how the call to
is still prefaced with the
pression operator. If it fails,PHP will issue a warning that may or may not be reported
or logged depending on the error reporting settings in
.These settings are dis-
cussed at length in Chapter 25, but you need to know that this warning will still be
issued regardless of whether you raise an exception.
Listing 7.5 Continued