PHP object-oriented programming (oop) learning notes (4)-exception handling class prediction_php tutorial

Source: Internet
Author: User
PHP object-oriented programming (oop) learning notes (4)-Exception handling class Exception. Exception handling modules similar to other languages are added for the use of PHP5. Exceptions in PHP code can be thrown by throw statements and captured by catch statements. Usage exceptions that require exception handling

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.

PHP5 adds exception handling modules similar to other languages. Exceptions in PHP code can be thrown by throw statements and captured by catch statements. Exception handling...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.