7.2 The Benefits of Exceptions

Nothing demonstrates the benefits of exceptions more than the previous section. Any time you can improve upon a piece of code and reduce the overall number of lines, it's a great change.

Another major boon from exceptions is that they "bubble up." When an exception isn't caught in the method it is thrown, the exception moves up a level in the call stack. In other words, the method that called the method gets a chance to handle the exception. This process continues until either the exception is finally caught or you're back in the top level. For example:

function createAddressBook( ) {

    $version = '1.0';

    $element = 'address-book';


    $dom = new DOMDocument($version);

    $ab = new DOMElement($element);

    $ab = $dom->appendChild($ab);

    return $dom;


try {

    $ab = createAddressBook( );

} catch (DOMException $e) {

    print $e;


Since createAddressBook( ) doesn't catch the exceptions it generates, the exceptions flow back up a level and can be caught in the try/catch block that wraps around the call to createAddressBook( ).

This behavior makes exceptions particularly well-suited for large-scale applications and frameworks. Without exceptions, you're forced to check the return value of every method, even at the relatively high level of development that occurs when you're combining full-blown objects.

However, at that point in your code, checking return values is not always useful, because there's very little you can do about a problem you discover. By the time it's reached that spot in the code, it's hard to tell whether the error was triggered by some truly nasty bug deep inside the bowels of your program, or whether it's a relatively benign warning that occurred one level down. As a result, you're likely to just log the error, display an innocuous message to the user, and quit.

With exceptions, this form of error handling is trivial. Additionally, it allows you to relocate the code to handle errors someplace out of the way, so your top-level application logic is easy to read and unencumbered by error handling.