O'Reilly logo

Upgrading to PHP 5 by Adam Trachtenberg

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required