Home > Backend Development > PHP Tutorial > Summary of exception handling methods in php, summary of php processing methods_PHP tutorial

Summary of exception handling methods in php, summary of php processing methods_PHP tutorial

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-07-13 10:10:01
Original
731 people have browsed it

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

The examples in this article summarize the exception handling methods in PHP. Share it with everyone for your reference. The specific analysis is as follows:

When an exception is triggered, it usually happens: An error exception handling module similar to other languages ​​was added in PHP5. Exceptions generated in PHP code can be thrown by the throw statement and caught by the catch statement. Code that requires exception handling must be placed in a try code block to catch possible exceptions. Every try must have at least one corresponding catch.

Use multiple catches to catch exceptions generated by different classes. When the try code block no longer throws exceptions or no catch can be found to match the thrown exception, the PHP code will jump to the last one. Execution continues after catch. Of course, PHP allows exceptions to be thrown again within the catch code block. When an exception is thrown, the subsequent code (Translator's Note: refers to the code block where the exception is thrown) will not continue to execute. PHP will try to find the first matching catch. If an exception is not caught and there is no need to use set_exception_handler() for corresponding processing, then PHP will generate a serious error and output Uncaught Exception ... (uncaught exception) prompt information.

1. Hierarchical relationship of exception classes, the code is as follows:

Copy code The code is as follows:
class NotFoundException extends Exception{}

class InputException extends Exception{}

class DBException extends Exception{}

2. Configure the handler for uncaught exceptions, the code is as follows:

Copy code The code is 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, if you manually throw a DBException but do not use try...catch to catch it, the exception will be handled by the PHP custom exception handler, the exception_uncaught_handler() function:
Copy code The code is 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 code The code is as follows:
if (0 != strcmp($curAlbum->interest_id, $it))

throw new NotFoundException('Sorry, the album you visited does not exist');

The above is the specific method of using PHP custom exception handler.

php example code is as follows:

Copy code The code is as follows:
class customException extends Exception
{
public function errorMessage()
{
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': '.$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 exception if email is not valid
throw new customException($email);
}
//check for "example" in mail address
if(strpos($email, "example") !== FALSE)
{
throw new Exception("$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. If any condition is not true, an exception is thrown.

1. The 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. If the e-mail address is illegal, the function returns an error message.

3. Execute the "try" code block. Under the first condition, no exception will be thrown.

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

5. The "catch" code block will catch the exception and display the appropriate error message.

If you do not catch the customException and catch the base exception tightly, handle the exception there and rethrow the exception. Sometimes, when an exception is thrown, you may want to handle it in a different way than the standard. You can Throw the exception again in a "catch" code block, the code is as follows:

Summary: There are three steps to use PHP exceptions:

Step one: Define the exception class. If not defined, use the system default exception class;

Step 2: When an exception occurs, use throw to throw an exception, such as ex1($num2); the parameter of the exception is $num2, which is obtained by the getMessage() of the exception;

Step 3: Trigger exception, use try clause, when the condition is met throw new ex1($num);

Step 4: catch exception catch (ex2 $e), which is equivalent to instantiating a defined exception class ex2 as $e;

Note that multiple exceptions can be defined, but only one can be triggered, which means that only one exception can be captured with catch.

Basic exception class, create a function that can throw an exception:

Copy code The code is as follows:
function num($num){
if ($num>1){//Exception throwing condition
$msg="Value cannot be greater than 1";//Exception message
throw new Exception($msg);//throw exception
}
echo "Number less than 1";
}
//Trigger exception in "try" code block
try {
num(3);
echo "executed normally";
}
//Catch exception
catch (Exception $e){
echo "Error message:".$e->getMessage();//Exception() system method to obtain exception information
echo "Error file:".$e->getFile();//The system method of Exception() gets the exception file name
echo "Number of lines:".$e->getLine();//The system method of Exception() gets the number of exception lines
}
//================================================ ======================
echo "
============================================ ============
";
//Extend basic exception class
function checkEmail($email){//Define a function that can throw an exception to determine the validity of EMAIL
if (filter_var($email,FILTER_VALIDATE_EMAIL)==false){
throw new checkEmailException($email);//throw exception and use EMAIL as parameter
}
echo "The email is legitimate";
}
class checkEmailException extends Exception{//Define extended exception class
public function errormsg(){
$msg="Error reason: ".$this->getMessage()." is not a legal EMAIL address!";
$msg.="Error file name:".$this->getFile();
$msg.="Error line number:".$this->getLine();
echo $msg;
}
}
$email="email…..@chhua.com";
try {//Trigger exception
checkEmail($email);
}
//Catch exception
catch (checkEmailException $e){
$e->errormsg();
}
//================================== Capture of multiple exceptions
echo "
============================================ =======
";
class ex1 extends Exception{//Define an exception class
public function msg(){
$msg="Error reason: ".$this->getMessage()." is 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{//Define an exception class
Public function msg(){
$msg="Error reason: ".$this->getMessage()." is equal to 100
";
$msg.="Error file:".$this->getFile()."
";
$msg.="Number of lines:".$this->getLine()."
";
echo $msg;
}
}
$num2=100;
try {
if ($num2>100){//Trigger when the condition is met
throw new ex1($num2);
}
if ($num2==100){//Triggered when the conditions are met
throw new ex2($num2);
}
}
catch (ex2 $e){//Catch the exception triggered
$e->msg();
}
catch (ex1 $e){//Catch the exception triggered
$e->msg();
}

I hope this article will be helpful to everyone’s PHP programming design.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/940486.htmlTechArticleA summary of exception handling methods in php, a summary of php processing methods. This article summarizes the exception handling methods in php. Share it with everyone for your reference. The specific analysis is as follows: When an exception is triggered,...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template