


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
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:
class InputException extends Exception{}
class DBException extends Exception{}
2. Configure the handler for uncaught exceptions, the code is as follows:
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:
if (false == is_resource($this->resConn))
throw new DBException('Database connection failed.'.mysql_error($this->resConn));
4. Business logic at a glance:
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:
{
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:
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.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7
