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.
The Code is as follows:
Exception {
/* Attribute */
Protected string $ message; // exception message content
Protected int $ code; // Exception code
Protected string $ file; // file name that throws an exception
Protected int $ line; // The row number in the file that throws an exception
/* 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) // returns the previous Exception in the Exception chain
Final public int getCode (void) // get the Exception Code
Final public string getFile (void) // obtain the name of the program file with an exception
Final public int getLine (void) // obtain the row number of the Code with an exception in the file
Final public array getTrace (void) // gets the exception tracking information
Final public string getTraceAsString (void) // gets the exception tracking information of the string type.
Public string _ toString (void) // convert an exception object to a 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.
The Code is as follows:
Function connectToDatabase ()
{
If (! $ Link = mysql_connect ("myhost", "myuser", "mypassw", "mybd "))
{
Throw new Exception ("cocould 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.
The Code is as follows:
Class MyException extends Exception
{
Protected $ ErrorInfo;
// Process some logic in the constructor and pass some information to the base class
Public function _ construct ($ message = null, $ code = 0)
{
$ This-> ErrorInfo = 'error message of custom error class ';
Parent: :__ construct ($ message, $ code );
}
// Provides methods for getting custom class information
Public function GetErrorInfo ()
{
Return $ this-> ErrorInfo;
}
/**
*
* Exception logs can also 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_handler sets 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.
The Code is as follows:
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.
The Code is as follows:
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.