Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 4 ■ EXCEPTIONS^39

Type hinting is especially important when working with customized exceptions. By using type
hinting and multiple catch blocks, you will be able to catch certain types of errors before others.
As explained earlier, catch blocks allow you to specify the type of exception to be caught,
and you can have multiple catch blocks. Think of this as if the instanceof operator were applied to
each catch block; if it returned true, then that block would be the one that was executed.
Listing 4-7 shows how to implement multiple catch blocks with different exception types.

Listing 4-7. Type Hinting Exceptions

class firstException extends Exception {}
class secondException extends Exception {}

try {
//Code that throws exceptions
} catch (firstException $e) {
//What to do when firstException is thrown
} catch (secondException $e) {
//What to do when secondException is thrown
} catch (Exception $e) {
//What to do for all other exceptions
}

Rethrowing Exceptions


Sometimes you will want to catch an exception, look at some of its properties, and then throw
it again. This is often useful to check an error code and decide whether it should be fatal.
Listing 4-8 demonstrates how to catch an exception, check its error code, and rethrow
the exception.

Listing 4-8. Rethrowing an Exception

function demonstration() {
try {
//Some code that throws exceptions
} catch (Exception $e) {
if($e->getCode() == 123) {
//Do something special for error code 123
} else {
throw $e;
}
}
}

This code will allow any exception that does not have the code 123 to bubble up to the
uncaught exception handler. The code 123 can then be handled in a special way, without
making a special subclassed exception.

McArthur_819-9C04.fm Page 39 Friday, February 1, 2008 10:25 AM

Free download pdf