Prev | Current Page 289 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"

The application attempts something.
2. If the attempt fails, the exception-handling feature throws an exception.
222 CHAPTER 8 ?–  ERRO R AND EXCEPTION HANDL ING
3. The assigned handler catches the exception and performs any necessary tasks.
4. The exception-handling feature cleans up any resources consumed during the
attempt.
Almost all languages have borrowed from the C++ language??™s handler syntax,
known as try/catch. Here??™s a simple pseudocode example:
try {
perform some task
if something goes wrong
throw exception("Something bad happened")
// Catch the thrown exception
} catch(exception) {
output the exception message
}
You can also set up multiple handler blocks, which allows you to account for a variety
of errors. You can accomplish this either by using various predefined handlers or by
extending one of the predefined handlers, essentially creating your own custom handler.
PHP currently only offers a single handler, exception. However, that handler can be
extended if necessary. It??™s likely that additional default handlers will be made available in
future releases. For the purposes of illustration, let??™s build on the previous pseudocode
example, using contrived handler classes to manage I/O and division-related errors:
try {
perform some task
if something goes wrong
throw IOexception("Could not open file.")
if something else goes wrong
throw Numberexception("Division by zero not allowed.


Pages:
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301