Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^40) CHAPTER 4 ■ EXCEPTIONS


Just the Facts


In this chapter, you were introduced to exceptions. You learned that the keywords try, catch
and throw, and the built-in Exception base class allow you to run error-prone sections of code
and recover from failure.
The try keyword defines a block of code to run, watching for thrown exceptions. You can
define multiple catch blocks for different types of exceptions.
You can throw the built-in Exception class using both variable and inline invocations. Prop-
erties that are available for inspection when an exception occurs include the message, code,
and trace information.
You can create custom exceptions for your applications by extending the built-in Exception
class. A key example is making your custom exceptions log to a file.
You can override the built-in exception handler by defining a set_exception_handler()
callback function and also get that to log all uncaught exceptions to a file.
Exceptions, however, come with a certain amount of overhead. You should avoid excessive
use of exceptions to control program flow.
You can centralize your error messages through the use of an error-coding class. This allows
you to create more manageable applications as your systems grow.
Type hinting applies to exceptions, and you can implement multiple catch blocks with
different exception types.
Finally, you can catch, inspect, and rethrow exceptions to the uncaught exception handler.

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

Free download pdf