PHP try, throw and catch

Source: Internet
Author: User
Tags getmessage

PHP try, throw and catch

Try, throw, and catch
    1. Try-the function that uses the exception should be in the "try" code block. If no exception is triggered, the code will continue to execute as usual. However, if an exception is triggered, an exception is thrown.
    2. Throw-this specifies how the exception is triggered. Each "throw" must correspond to at least one "catch"
    3. Catch-the "catch" code block catches an exception and creates an object that contains the exception information

Let's trigger an exception:



function Checknum ($number)
{
if ($number >1) {
throw new Exception ("Value must be 1 or below");
}
return true;
}

Try {
Checknum (2);
If the exception is a thrown, this text won't be shown Echo's If you see this , the number is 1 or below '; }
Catching exceptions
catch (Exception $e)
{ echo ' Message: '. $e->getmessage ();

The above code will get an error like this:

Example Explanation:

The above code throws an exception and captures it:

    1. Create the Checknum () function. It detects if the number is greater than 1. If it is, an exception is thrown.
    2. Call the Checknum () function in the "Try" code block.
    3. The exception in the Checknum () function is thrown
    4. The catch code block receives the exception and creates an object ($e) that contains the exception information.
    5. Output the error message from this exception by calling $e->getmessage () from this exception object

However, to follow the principle that each throw must correspond to a catch, you can set up a top-level exception handler to handle the missing error.

PHP try, throw and catch

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.