PHP Exception Handling

Source: Internet
Author: User

The first thing to happen is an exception!

The so-called occurrence, refers to throwing an exception!

Then deal with the exception!

The so-called treatment, that is, once an anomaly occurs, to get and deal with this anomaly, there are usually two stages: monitoring and capturing!

Process:

1. Throw Exception Throw

2. Listen for exception try

3. Catching exception catch

Note: the exception here, in fact, is an exception object, this object must be the system pre-defined exception class (class named Exception) or its subclasses instantiated!

Example:

<?PHPEcho"<meta charset=utf-8>";classgoods{ Public functionGetPrice () {$price=$_get[' P ']; //exception Handling If the price is less than 0        if($price<0) {            //instantiate an exception object            $e=New Exception($message= ' Price cannot be negative! ‘); Throw $e;//Throw Exception}Else{            Echo $price; }    }}//Exception HandlingTry{    //listen to the code    $good=NewGoods; $good-GetPrice ();}Catch(Exception $e){    //Catching exceptions    Echo"Error message is:".$e->getmessage (). " <br/> "; Echo"Error code is:".$e->getcode (). " <br/> "; Echo"Error file is:".$e->getfile (). " <br/> "; Echo"The error line number is:".$e->getline (). " <br/> ";}

Results: The input parameter p=22 (greater than 0) shows normal, not throwing an exception!

If the parameter p=-22 (less than 0) is passed, the result is as follows

The next article introduces the exception handling in PDO

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.