In this second part of a two-part series on error and exception handling in PHP, we focus specifically on handling exceptions. This article is excerpted from chapter 8 of the book Beginning PHP and Oracle: From Novice to Professional, written by W. Jason Gilmore and Bob Bryla (Apress; ISBN: 1590597702).
This section introduces PHP’s exception-handling feature. Specifically, we touch upon the base exception class internals and demonstrate how to extend this base class, define multiple catch blocks, and introduce other advanced handling tasks. Let’s begin with the basics: the base exception class.
Extending the Base Exception Class
PHP’s base exception class is actually quite simple in nature, offering a default constructor consisting of no parameters, an overloaded constructor consisting of two optional parameters, and six methods. Each of these parameters and methods is introduced in this section.
The Default Constructor
The default exception constructor is called with no parameters. For example, you can invoke the exception class like so:
throw new Exception();
Once the exception has been instantiated, you can use any of the six methods introduced later in this section. However, only four will be of any use; the other two are useful only if you instantiate the class with the overloaded constructor, introduced next.
The Overloaded Constructor
The overloaded constructor offers additional functionality not available to the default constructor through the acceptance of two optional parameters:
message: Intended to be a user-friendly explanation that presumably will be passed to the user via thegetMessage()method, introduced in the following section.
error code: Intended to hold an error identifier that presumably will be mapped to some identifier-to-message table. Error codes are often used for reasons of internationalization and localization. This error code is made available via thegetCode()method, introduced in the next section. Later you’ll learn how the base exception class can be extended to compute identifier-to-message table lookups.
You can call this constructor in a variety of ways, each of which is demonstrated here:
throw new Exception("Something bad just happened", 4) throw new Exception("Something bad just happened"); throw new Exception("", 4);
Of course, nothing actually happens to the exception until it’s caught, as demonstrated later in this section.