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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access