PHP object-oriented programming and design patterns (4 ). PHP advanced programming study notes exceptions are often used to handle various types of errors encountered during normal program execution. For example, when you do database links, you need to process several PHP advanced programming learning notes for 2014.06.12
Exceptions are often used to handle various types of errors encountered during normal program execution. For example, you need to handle database connection failures during database connection. Exceptions can improve the fault tolerance feature of our programs, so that our applications are more stable and robust.
Usage exception
PHP5 adds exception handling modules similar to other languages. Exceptions in PHP code can be thrown by throw statements and captured by catch statements. All codes that require exception handling must be placed in the try code block to capture possible exceptions. Each try corresponds to at least one catch block. Multiple catch methods can capture exceptions generated by different classes. When the try code block does not throw an exception or the catch code cannot be found to match the Exception thrown, the PHP code will continue to be executed after the jump to the last catch. Of course, PHP allows another throw exception to be thrown in the catch code block.
Predefined Exception
The Exception class is the base class of all exceptions. we can derive the Exception class to customize exceptions. The following list lists the basic information about the Exception.
Exception {/* attribute */protected string $ message; // The content of the Exception message protected int $ code; // The Exception code protected string $ file; // the file name that throws an exception: protected int $ line; // the row number/* method */public _ construct ([string $ message = ""[, int $ code = 0 [, Exception $ previous = NULL] // Exception constructor final public string getMessage (void) // Get The Exception Message Content final public Exception getPrevious (void) // return the previous Exception final public int getCode (void) in the Exception chain) // Obtain the exception code final public string getFile (void) // Obtain the name of the program file with the exception final public int getLine (void) // obtain the final public array getTrace (void) row number of the code with an exception in the file // Obtain the exception tracing information final public string getTraceAsString (void) // Obtain the exception tracking information of the string type public string _ toString (void) // Convert the exception object to the string final private void _ clone (void) // exception clone}
After learning about the Exception, we will try to extend the exception class to implement a custom Exception.
function connectToDatabase(){ if(!$link = mysql_connect("myhost","myuser","mypassw","mybd")) { throw new Exception("could not connect to the database."); }}try{ connectToDatabase();}catch(Exception $e){echo $e->getMessage();}
Here we throw an Exception of the Exception type and catch this Exception, and finally print "cocould not connect to the database .". You may want to display the cause of database connection failure. The following describes how to implement custom information by extending the exception class.
Class MyException extends Exception {protected $ ErrorInfo; // process some logic in the constructor, and then pass some information to the base class public function _ construct ($ message = null, $ code = 0) {$ this-> ErrorInfo = 'Error message for custom error class'; parent :__ construct ($ message, $ code );} // provides a method to obtain custom class information: public function GetErrorInfo () {return $ this-> ErrorInfo;}/***** exception logs can be added here, you only need to call the above constructor. **/public function log ($ file) {file_put_contents ($ fiel, $ this->__ toString (), FILE_APPEND );}} function connectToDatabase () {throw new MyException ("ErrorMessage");} try {connectToDatabase ();} catch (MyException $ e) {echo $ e-> getMessage (). "\ n"; echo $ e-> GetErrorInfo ();}
Set_exception_handlerSet a user-defined exception handling function
When an uncaptured exception occurs, the called function name is used as the parameter of set_exception_handler. This function must be defined before set_exception_handler () is called. This function accepts a parameter, which is a thrown exception object. This can be used to improve the exception log processing mentioned above.
function ExceptionLogger($exception){ $file='ExceptionLog.log'; file_put_contents($fiel,$exception->__toString(),FILE_APPEND);}set_exception_handler(ExceptionLogger);
1.3. PHP allows a throw exception to be thrown again in the catch code block.
Try {# code ...} catch (Exception $ e) {if ($ e-> getCode () = 999) {# perform some operations} else {throw $ e ;}}
Summary
Exception functions are very powerful, but we do not think we can abuse the exception mechanism in the project, especially the mechanism that uses exception logs in large quantities, this greatly increases system overhead and reduces application performance. With the error code, we can easily manage the error information. When an error message is flushed multiple times, using the error code is a scientific choice. We can even use the error code to display error messages in multiple languages.
Pipeline learning notes exceptions are often used to handle various types of errors encountered during normal program execution. For example, when you create a database link, you need to process the data...