PHP object-oriented programming and design patterns (4) _php tutorial

Source: Internet
Author: User
PHP Advanced Programming Learning Note 2014.06.12

Exceptions are often used to handle various types of errors encountered during normal execution of a program. For example, when you do a database link, you need to handle the database connection failure. Using exceptions can improve the fault-tolerant nature of our programs, which makes our applications more stable and robust.

Using exceptions

PHP5 adds an exception handling module similar to other languages. Exceptions generated in PHP code can be thrown by a throw statement and captured by a catch statement. Code that requires exception handling must be placed inside a try code block to catch possible exceptions. Each try corresponds to at least one catch block. You can use multiple catches to catch exceptions that are generated by different classes. When the try code block no longer throws an exception or cannot find a catch that matches the thrown exception, the PHP code resumes execution after jumping to the last catch. Of course, PHP allows you to throw (throw) exceptions again within a catch code block.

Pre-defined exception Exception

The Exception class is the base class for all exceptions, and we can derive the Exception class to achieve the purpose of the custom exception. The following checklist lists the basic information for Exception.

Exception {    /*Properties*/    protected string $message;//Exception message Content    protectedInt$code;//Exception Code    protected string $file;//the file name that throws the exception    protectedInt$line;//throws the line number of the exception in the file    /*Method*/     Public__construct ([string $message= "" [, int$code= 0 [,Exception $previous=NULL]]] )//Exception Constructors    Final  Public stringGetMessage (void)//get exception message content    Final  Public ExceptionGetPrevious (void)//returns the previous exception in the chain of exceptions    Final  Publicint GetCode (void)//Get Exception Code    Final  Public stringGetFile (void)//Gets the program file name of the exception that occurred    Final  Publicint getLine (void)//gets the line number of the code in the file where the exception occurred    Final  Public ArrayGettrace (void)//get exception tracking information    Final  Public stringGettraceasstring (void)//get exception tracking information for a string type     Public string__tostring (void)//To convert an exception object to a string    Final Privatevoid __clone (void)//Exception Cloning}

Once you know Exception, let's try extending the Exception class to implement a custom exception.

function connecttodatabase () {        if(!  $linkmysql_connect("Myhost", "MyUser", "MYPASSW", "MYBD"))    {        throw  NewException("Could not connect to the database.") );    }} Try {    connecttodatabase ();} Catch (Exception$e) {echo$e, GetMessage ();}

Here we throw an exception of the class Exception type, and catch the exception in the catch, and finally print out "could not connect to the database." Maybe you want to. Displays information about the reason for the database connection failure. Below and by extending the exception class to implement our custom information.

classMyExceptionextends Exception{    protected $ErrorInfo; //The constructor handles some logic and then passes 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 methods for getting custom class information     Public functionGetErrorInfo () {return $this-errorinfo; }    /** * * You can also add an exception log, just call it in the constructor above **/     Public function Log($file)    {        file_put_contents($fiel,$this->__tostring (),file_append); }}functionconnecttodatabase () {Throw NewMyException ("ErrorMessage");}Try{connecttodatabase ();}Catch(myexception$e){        Echo $e->getmessage (). "\ n"; Echo $e-GetErrorInfo ();}

Set_exception_handler Setting a user-defined exception handling function

When an uncaught exception occurs, the function name that is called as the Set_exception_handler parameter. The function must be defined before calling Set_exception_handler (). The function takes a parameter, which is an exception object that is thrown. 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 you to throw (throw) exceptions again within a catch code block.

Try {    #code ... }catch(Exception$e) {    if($e->getcode () = =999    )        {# take some action     }Else     {        throw$e;            }}

Summarize

The functionality of the exception is very powerful, but not for the misuse of the exception mechanism that we can arbitrarily abuse in the project, especially the large number of mechanisms that use the Exception log, which greatly increases system overhead to reduce the performance of the application. With error codes we can easily manage error messages, and when an error message is thrown multiple times, using the error code is a scientific choice. We can even use the error code to let the error message also support multi-language display.

http://www.bkjia.com/PHPjc/781920.html www.bkjia.com true http://www.bkjia.com/PHPjc/781920.html techarticle PHP Advanced Programming Learning Notes 2014.06.12 Exceptions are often used to handle various types of errors encountered during normal execution of the program. such as database links, you have to deal with the number of ...

  • 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.