11.07.2015 Views

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 8 • ERROR AND EXCEPTION HANDLINGwww.it-ebooks.infoThis snippet would produce a log entry in the messages syslog file similar to the following:Dec 5 20:09:29 CHP8[30326]: Chapter 8 example warning.Exception HandlingLanguages such as Java, C#, and Python have long been heralded for their efficient error-managementabilities, accomplished through the use of exception handling. As of version 5, <strong>PHP</strong> was added to the listof languages supporting this great feature. In this section, you’ll learn all about exception handling,including the basic concepts, syntax, and best practices. Because exception handling is new to <strong>PHP</strong>, youmay not have any prior experience incorporating this feature into your scripts. Therefore, a generaloverview is presented regarding the matter. If you’re already familiar with the basic concepts, feel free toskip ahead to the <strong>PHP</strong>-specific material later in this section.Why Exception Handling Is HandyIn a perfect world, your program would run like a well-oiled machine, devoid of both internal and userinitiatederrors that disrupt the flow of execution. However, programming, like the real world, ofteninvolves unforeseen happenings that disrupt the flow of events. In programmer’s lingo, theseunexpected happenings are known as exceptions. Some programming languages have the capability toreact gracefully to an exception, a behavior known as exception handling. When an error is detected, thecode issues, or throws, an exception. In turn, the error-handling code takes ownership of the exception,or catches it. The advantages to such a strategy are many.For starters, exception handling brings order to the error identification and management processthrough the use of a generalized strategy for not only identifying and reporting application errors, butalso specifying what the program should do once an error is encountered. Furthermore, exceptionhandlingsyntax promotes the separation of error handlers from the general application logic, resultingin considerably more organized, readable code. Most languages that implement exception handlingabstract the process into four steps:1. The application attempts to perform some task.2. If the attempt fails, the exception-handling feature throws an exception.3. The assigned handler catches the exception and performs any necessary tasks.4. The exception-handling feature cleans up any resources consumed during theattempt.Almost all languages have borrowed from the C++ syntax, known as try/catch. Here’s a simplepseudocode example:182

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!