Exception Handling try-catch-finally

Source: Internet
Author: User
Tags exit in

Added the Finally module in php5.5.

Try {
// Do it well. Don't be afraid of any problems. Someone else can handle them.
} Catch (HttpException $ e ){
// Always prepare to handle the HTTP problem thrown above
} Catch (Exception $ e ){
// Always prepare for handling problems that none of them can handle
} Finally {
// Clean the battlefield and leave after all.
}


After return in try, finally continues execution. If return exists in finally, the final return value is the return value in finally.
The finally statement is not executed after die or exit in try.

Example01:

<? Php/** finally block is a good design. The return statement can overwrite the return statement in other blocks, the exception thrown by try catch does not need to be nested by try-catch to handle the exception thrown by the child try-catch. This is the same as that thrown by java, c # If the return statement exists in the finally block, compile time error (compile-time error) will be thrown */function asdf () {try {throw new Exception ('error ');} catch (Exception $ e) {echo "An error occurred"; throw $ e ;} finally {// This overrides the exception as if it were never thrown return "\ nException erased" ;}}try {echo asdf ();} catch (Exception $ e) {echo "\ nResult :". $ e-> getMessage ();}/* The output from above will look like this: An error occurred Exception erased Without the return statement in the finally block it wowould look like this: an error occurred Result: error */


Example02:

<? Php/** has an opposite behavior in PHP 5.5.3's finally and return statements: In a method, a variable is returned for a try block, and the finally block modifies the variable, the returned result is modified by finally. However, when the variables returned by the try block are involved in the calculation (evaluated in-line), the modification of the finally block to this variable is ignored (unknown reason ...) */function returnVariable () {$ foo = 1; try {return $ foo;} finally {$ foo ++ ;}} function returnVariablePlusZero () {$ foo = 1; try {return $ foo + 0;} finally {$ foo ++; }}$ test1 = returnVariable (); // returns 2, not the correct value of 1. $ test2 = returnVariablePlusZero (); // returns correct value of 1, but inconsistent with $ test1.


Example03:

<? Php/** small example verification variable check if the name contains only letters, and does not contain the word name */$ name = "Name "; try {// preg_match () returns the matching times of pattern. Its value will be 0 (not matched) or 1 time, because preg_match () will stop searching after the first match. Different from this, preg_match_all () searches for subject until it reaches the end. If an error preg_match () occurs, FALSE is returned. If (preg_match ('/[^ a-z]/I', $ name) {throw new Exception ("$ name contains character other than a-z A-Z ");} if (strpos (strtolower ($ name), 'name ')! = False) {throw new Exception ("$ name contains the word name");} echo "The Name is valid";} catch (exception $ e) {throw new Exception ("insert name again", 0, $ e) ;}} catch (exception $ e) {if ($ e-> getPrevious ()) {echo "The Previous Exception is :". $ e-> getPrevious ()-> getMessage (). "<br/>";} echo "The Exception is :". $ e-> getMessage (). "<br/> ";}


Example04

<? Php/* When catching an exception inside a namespace it is important that you escape to the global space: how to escape from the namespace */namespace SomeNamespace; class SomeClass {function SomeFunction () {try {throw new Exception ('some Error message');} catch (\ Exception $ e) {var_dump ($ e-> getMessage ());}}} // error: // Fatal error: Class 'somenamespace \ exception' not found in C: \ xampp \ htdocs \ tonglei \ index. php on line 8


Example05

<? Php // the following code will report T_THROW Syntax Error. someFunction () OR throw new Exception (); // This method can be used in the following correct form: function throwException ($ message = null, $ code = null) {throw new Exception ($ message, $ code);} someFunction () OR throwException ();

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.