PHP Exception Handling

Source: Internet
Author: User

one, exception Handling--can effectively control multiple errors or exceptions in the code

    • The basic syntax is as follows:
Try {  // code for possible exception } Catch (Exception$e) {  // for exception handling//1, self-processing//2, no processing, continue to throw }

Exception is a PHP built-in exception handling class

    

    • Example
<?PHPfunctionAddUser ($name){        if($name= = "abc"){            Echo"added successfully! "; }Else{            //Throw Exception            Throw New Exception("add failed! "); }    }    functionUpdateUser ($name){        if($name= = "abc"){            Echo"modified successfully!" "; }Else{            //Throw Exception            Throw New Exception("modification Failed!") "); }    }    Try{addUser ("abc"); UpdateUser ("Ben."); }    //Catching exceptions    Catch(Exception $e){        Echo"failure message:".$e-GetMessage ();
Throw $e; can also continue to be thrown after capture}?>

The results of the operation are as Follows:

second, top-level exception Handling--catch exceptions that are not caught

    • The basic usage is as follows:
<? PHP      function myexception ($exception) {             echo "exception information:".  $exception-getMessage ();     }      Set_exception_handler ("myexception");      Throw New Exception ("no catch exception");? >
    • Example
1<?PHP2     //customizing a top-level exception handling function3     functionMyException ($exception){4         Echo"exception information:".$exception-getMessage ();5     }6     //to modify the default top-level exception handling function (device)7     Set_exception_handler("myexception");8 9     functionA$age){Ten         if($age>100) one             Throw New Exception("too Old!") "); a     } -  -A (120);  the?>

Results:

third, Summary: If an exception is thrown, it must be captured or handled with the top-level exception handler.

    

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