11.07.2015 Views

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

www.it-ebooks.infoCHAPTER 8 • ERROR AND EXCEPTION HANDLINGgetPrevious(): Added in <strong>PHP</strong> 5.3.0, this method will return the previous exception,presuming it was passed via the exception constructor.getTrace(): Returns an array consisting of information pertinent to the context inwhich the error occurred. Specifically, this array includes the file name, line,function, and function parameters.getTraceAsString(): Returns all of the same information as is made available bygetTrace(), except that this information is returned as a string rather than as anarray.■ Caution Although you can extend the exception base class, you cannot override any of the preceding methodsbecause they are all declared as final. See Chapter 6 more for information about the final scope.Listing 8-1 offers a simple example that embodies the use of the overloaded base class constructorand several of the methods.Listing 8-1. Raising an Exceptiontry {$fh = fopen("contacts.txt", "r");if (! $fh) {throw new Exception("Could not open the file!");}}catch (Exception $e) {echo "Error (File: ".$e->getFile().", line ".$e->getLine()."): ".$e->getMessage();}If the exception is raised, something like the following would be output:Error (File: /usr/local/apache2/htdocs/8/read.php, line 6): Could not open the file!Extending the Exception ClassAlthough <strong>PHP</strong>’s base exception class offers some nifty features, in some situations you’ll likely want toextend the class to allow for additional capabilities. For example, suppose you want to internationalizeyour application to allow for the translation of error messages. These messages reside in an array locatedin a separate text file. The extended exception class will read from this flat file, mapping the error codepassed into the constructor to the appropriate message (which presumably has been localized to theappropriate language). A sample flat file follows:185

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

Saved successfully!

Ooh no, something went wrong!