PHP 5 introduced a new way of handling errors known as exceptions, a concept that is common in many other languages. An exception is when something goes wrong in a block of code. Instead of handling the error at that particular point, you throw the exception and catch it in a special block. This has the advantage of keeping all your error handling in a single place, rather than being scattered throughout your script. PHP has a built-in Exception class, which you can either use as is, or extend to create your own custom
exceptions. If you’re new to exceptions, it might sound esoteric, but it’s quite simple in practice. First, let’s look at how to throw an exception.


Throwing an exception
When writing scripts, it’s normal practice to test the type of data passed to a function. This often results in complex conditional statements that determine what should happen if the data is of the wrong type. The advantage of using exceptions is that it reduces complexity by handling what should be done in a separate part of the script. This is particularly important with OOP, because classes should be designed to be as project neutral as possible. So, when a problem arises with data passed to a method, keep things simple by throwing an exception inside the method, and leave it to the main application script to determine how
to handle it. The way you throw an exception is with the throw keyword like this:

if (the sky falls in) {
throw new Exception('Oops, the sky has fallen in!');
}

Following the throw keyword, you instantiate a new Exception object, which takes one argument: a string that identifies the nature of the problem. Technically speaking, this argument is optional; if you omit it, PHP uses the default value, “Unknown exception.” You can also pass a number as an optional second argument. The number has no significance other than to identify the exception. This allows you to set up your own system of error codes.

Once an exception has been thrown, it needs to be caught.

Catching an exception
Whenever you use code that might throw exceptions, wrap the code in a try block and catch any exceptions in a catch block. This structure is similar to an if . . . else conditional statement, except that it uses try and catch instead of if and else. The basic structure looks like this:


try {
// code that might throw exceptions
} catch (Exception $e) {
// handle the exception here
}

The try block could be dozens, even hundreds of lines long. If the code throws an exception, the script jumps immediately to the catch block, where the code decides how to handle the problem. In a development environment, you normally want to display a descriptive error message; but in a production environment, you could redirect the user to a custom error page, while sending an email with details of the problem to the server administrator.

The parentheses after the catch keyword should contain a variable to capture the details of the exception. It’s also a good idea to use type hinting (see “Restricting acceptable data with type hinting” earlier in the chapter) to indicate what type of exception you want to deal with. In addition to the basic Exception class, the Standard PHP Library (SPL) defines a number of specialized exception classes that you can use in your class definitions. You can also create your own custom exceptions. Using different types of exceptions enables you to have multiple catch blocks that handle problems in different ways. For example, you might create custom exceptions called InvalidDataException and DatabaseErrorException. You could then handle them like this:

try {
// script to be processed
} catch (InvalidDataException $e) {
// redirect user to input page with appropriate error message
} catch (DatabaseErrorException $e) {
// redirect user to database error page
} catch (Exception $e) {
// handle any generic exceptions
}

The catch block for generic exceptions must come last. Otherwise the type hinting won’t work, as custom exceptions need to extend the built-in Exception class, and therefore belong to the same data type.