Summary of exception handling methods in PHP, summary of PHP processing methods _php Tutorial

Source: Internet
Author: User
Tags throw exception

Summary of exception handling methods in PHP, summary of PHP processing methods


This paper summarizes the exception handling methods in PHP. Share to everyone for your reference. The specific analysis is as follows:

When an exception is triggered, it usually occurs when an error exception handling module similar to other languages is added to the PHP5. Exceptions generated in PHP code can be thrown by a throw statement and captured by a catch statement. The code that requires exception handling must be placed inside a try code block to catch possible exceptions. Each try must have at least one catch corresponding to it.

Multiple catches can be used to catch exceptions from different classes, and when a 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 the exception to be thrown in the catch code block again, and when an exception is thrown, the code behind it (the code block where the exception was thrown) will not continue, and PHP will try to find the first catch that matches it, if an exception is not caught, And without using Set_exception_handler () for the appropriate processing, then PHP will produce a serious error, and output uncaught exception ... (The exception is not caught) prompt information.

1, the level of the exception class relationship, the code is as follows:
Copy the Code code as follows: Class Notfoundexception extends exception{}

Class Inputexception extends exception{}

Class Dbexception extends exception{}

2. Configure the processor that does not catch the exception, the code is as follows:
Copy the Code code as follows: function Exception_uncaught_handler (Exception $e) {
Header (' content-type:text/html; Charset=utf-8 ');
if ($e instanceof notfoundexception)
Exit ($e->getmessage ());
ElseIf ($e instanceof dbexception)
Exit ($e->getmessage ());
Else
Exit ($e->getmessage ());
}
Set_exception_handler (' Exception_uncaught_handler ');
3, in the database connection code, manually throw dbexception exception but not using Try...catch for capture processing, the exception will be PHP custom exception handler, Exception_uncaught_handler () function processing:
Copy the code as follows: $this->resconn = mysql_connect ($CONFIGS [' Db_host '], $CONFIGS [' Db_user '], $CONFIGS [' db_pwd ']);
if (false = = Is_resource ($this->resconn))
throw new Dbexception (' Database connection failed. '. Mysql_error ($this->resconn));
4, business logic at a glance:
Copy the code as follows: if (0! = strcmp ($curAlbum->interest_id, $it))

throw new Notfoundexception (' Sorry, the album you are visiting does not exist ');

The above is the specific use of PHP custom exception handler.

The

PHP instance code is as follows:
Copy the code code as follows: <?php
class Customexception extends Exception
{
Public function ErrorMessage ()
{
//error message
$ERRORMSG = ' Error on line '. $this->getline (). ' $this->ge Tfile ()
. ': '. $this->getmessage (). ' is not a valid e-mail address ';
return $ERRORMSG;
}
}

$email = "someone@example.com";

Try
{
//check if
if (Filter_var ($email, filter_validate_email) = = = FALSE)
{
//throw excep tion if email is not valid
throw new Customexception ($email);
}
//check for ' example ' in mail address
if (Strpos ($email, "example")!== FALSE)
{
throw new Excep tion ("$email is an example e-mail");
}
}

catch (customexception $e)
{
echo $e->errormessage ();
}

catch (Exception $e)
{
echo $e->getmessage ();
}
?
Example Explanation: The above code tests two conditions, and throws an exception if any condition is not true.

The 1.customException () class is created as an extension of the old exception class so that it inherits all the properties and methods of the old class.

2. Create the ErrorMessage () function, and if the e-mail address is not valid, the function returns an error message.

3. Execute "Try" code block, under the first condition, will not throw an exception.

4. Since e-mail contains the string "Example", the second condition will trigger an exception.

5. The catch block catches the exception and displays the appropriate error message.

If you do not capture customexception and tightly capture the base exception, handle the exception there, re-throw the exception, and sometimes, when the exception is thrown, you may want to handle it in a different way from the standard, in a "catch" The code block throws an exception again with the following code:

Summary: The use of PHP exceptions is divided into three steps:

The first step: Define the Exception class, if you do not define the system default exception class;

The second step: Throw an exception with throw when an exception occurs, such as EX1 ($num 2), and the exception parameter is $num2 with the getmessage () of the exception;

The third step: Trigger the exception, with a try clause, when the condition is met throw new Ex1 ($num);

Fourth step: Catch catching Exception catch (Ex2 $e), equivalent to instantiate a well-defined exception class EX2 to $e;

Note that exceptions can define multiple, but only one, which means that only one exception is caught with a catch.

A basic exception class that creates a function that throws an exception:
Copy CodeThe code is as follows: function num ($num) {
if ($num >1) {//exception throw condition
$msg = "value cannot be greater than 1″;//exception hint information
throw new Exception ($msg);//Throws an exception
}
echo "Value less than 1 ″;
}
To trigger an exception in a "try" code block
try {
Num (3);
echo "performs normally";
}
Catching exceptions
catch (Exception $e) {
echo "error message:". $e->getmessage ();//exception () system method gets exception information
echo "Error file:". $e->getfile ();//exception () system method gets the exception file name
echo "Number of lines:". $e->getline (); System method for//exception () gets the number of exception rows
}
//======================================================================
echo "
========================================================
";
Extending the base Exception class
function Checkemail ($email) {//define an exception that can be thrown to judge the legality of an email
if (Filter_var ($email, Filter_validate_email) ==false) {
throw new Checkemailexception ($email);//throw exception with email parameters
}
echo "Mail Legal";
}
Class Checkemailexception extends exception{//defining extended exception classes
Public Function errormsg () {
$msg = "Error Reason:". $this->getmessage (). " Not a legitimate email address! ";
$msg. = "Error file name:". $this->getfile ();
$msg. = "Number of error lines:". $this->getline ();
Echo $msg;
}
}
$email = "Email ... @chhua. com";
try {//Trigger exception
Checkemail ($email);
}
Catching exceptions
catch (Checkemailexception $e) {
$e->errormsg ();
}
================================== multiple exception captures
echo "
===================================================
";
Class Ex1 extends exception{//defines an exception
Public Function msg () {
$msg = "Error Reason:". $this->getmessage (). " Greater than 100
";
$msg. = "Error file:". $this->getfile (). "
";
$msg. = "Error code:". $this->getcode (). "
";
$msg. = "Number of lines:". $this->getline (). "
";
Echo $msg;
}
}
Class Ex2 extends exception{//defines an exception
Public Function msg () {
$msg = "Error Reason:". $this->getmessage (). " equals 100
";
$msg. = "Error file:". $this->getfile (). "
";
$msg. = "Number of lines:". $this->getline (). "
";
Echo $msg;
}
}
$num 2=100;
try {
if ($num 2>100) {//trigger when condition is met
throw new Ex1 ($num 2);
}
if ($num 2==100) {//trigger when condition is met
throw new Ex2 ($num 2);
}
}
catch (Ex2 $e) {//captures the triggered exception
$e->msg ();
}
catch (Ex1 $e) {//captures the triggered exception
$e->msg ();
}

I hope this article is helpful to everyone's PHP programming.

http://www.bkjia.com/PHPjc/940486.html www.bkjia.com true http://www.bkjia.com/PHPjc/940486.html techarticle Summary of exception handling methods in PHP, summary of PHP processing methods This article summarizes the exception handling methods in PHP. Share to everyone for your reference. The specific analysis is as follows: When the exception is triggered, pass ...

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