Home Backend Development PHP Tutorial How PHP throws exception handling errors_PHP tutorial

How PHP throws exception handling errors_PHP tutorial

Jul 21, 2016 pm 03:31 PM
exception php What exist deal with how abnormal Throw yes Know mistake

First of all, you need to know what is a PHP exception?

Exception is used to change the normal flow of the script when a specified error occurs.
PHP 5 provides a new object-oriented error handling method.
Exception handling is used to change the normal flow of the script when a specified error (exception) situation occurs. This situation is called an exception.

When an exception is triggered, what typically happens is:

The current code state is saved
Code execution is switched to a predefined exception handler function
According to the situation, the handler Perhaps restart code execution from a saved code state, terminate script execution, or continue script execution from another location in the code
We will show different error handling methods:

Basic use of exceptions
Create a custom exception handler
Multiple exceptions
Rethrow exceptions
Set a top-level exception handler
Basic usage of exceptions
When an exception is thrown, the code that follows it Execution will not continue and PHP will try to find a matching "catch" block of code.

If the exception is not caught and there is no need to use set_exception_handler() for corresponding processing, then a serious error (fatal error) will occur and "Uncaught Exception" will be output. error message.

Let's try throwing an exception without catching it:

Copy code The code is as follows:

//create function with an exceptionfunction
checkNum($number) {
if($number>1) {
throw new Exception(”Value must be 1 or below ");
} return true;
}
//trigger
exceptioncheckNum(2);
?>

The above code will get something like this An error:

Fatal error: Uncaught exception 'Exception' with message 'Value must be 1 or below' in C:webfoldertest.php:6 Stack trace: #0 C:webfoldertest.php(12): checkNum(28) #1 {main} thrown in C:webfoldertest.php on line 6
Try, throw and catch
To avoid the errors in the above example, we need to create appropriate code to handle exceptions.

Handling handlers should include:

Try - Functions that use exceptions should be inside a "try" block. If no exception is triggered, the code continues execution as usual. But if an exception is triggered, an exception will be thrown.
Throw - This specifies how to trigger the exception. Each "throw" must correspond to at least one "catch"
Catch - The "catch" code block will catch the exception and create an object containing the exception information
Let us trigger an exception:

< ;?php//Create a function that can throw an exception function checkNum($number) { if($number>1) { throw new Exception("Value must be 1 or below"); } return true; }//In The exception is triggered in the "try" code block try { checkNum(2); //If the exception is thrown, this text will not be shown echo 'If you see this, the number is 1 or below'; }//Catch the exception catch (Exception $e) { echo 'Message: ' .$e->getMessage(); }?>
The above code will get an error similar to this:

Message: Value must be 1 or Below
example explanation:
The above code throws an exception and catches it:

Create the checkNum() function. It detects whether the number is greater than 1. If so, throw an exception.
Call the checkNum() function in the “try” code block.
Exception in checkNum() function is thrown
The "catch" code block receives the exception and creates an object ($e) containing the exception information.
By calling $e->getMessage() from this exception object, the error message from the exception is output.
However, in order to follow the principle of "each throw must correspond to a catch", a top-level exception can be set processor to handle missed errors.
Create a custom Exception class
Creating a custom exception handler is very simple. We simply created a specialized class whose functions are called when an exception occurs in PHP. This class must be an extension of the exception class.

This custom exception class inherits all properties of PHP's exception class, and you can add custom functions to it.

We start to create the exception class:
Copy the 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);
}
}catch (customException $e)
{
// display custom message
echo $e->errorMessage();
}?>

This new class is a copy of the old exception class, plus the errorMessage() function. Just because it is a copy of the old class, it inherits the properties and methods from the old class, and we can use the methods of the exception class, such as getLine(), getFile(), and getMessage().

Explanation of the example:
The above code throws an exception and catches it through a custom exception class:

The customException() class is used as the old exception class Created by an extension. This way it inherits all properties and methods of the old class.
Create errorMessage() function. If the e-mail address is illegal, the function returns an error message
Set the $email variable to an illegal e-mail address string
Execute the "try" code block, because the e-mail address is illegal , thus throwing an exception
The "catch" code block catches the exception and displays the error message
Multiple exceptions
You can use multiple exceptions for a script to detect multiple situations.

You can use multiple if..else code blocks, or a switch code block, or nest multiple exceptions. These exceptions can use different exception classes and return different error messages:
Copy code The code is as follows:

< ?php
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(); }?>

Explanation of the example:
The above code tests two conditions. If any condition is not true, an exception is thrown:

The customException() class was created as an extension of the old exception class. This way it inherits all properties and methods of the old class.
Create errorMessage() function. If the e-mail address is not valid, this function returns an error message.
Execute the "try" code block, and in the first condition, no exception will be thrown.
Since the e-mail contains the string "example", the second condition will trigger an exception.
The "catch" code block will catch the exception and display the appropriate error message
If customException is not caught, the base exception is caught tightly and the exception is handled there.
Rethrowing exceptions
Sometimes, when an exception is thrown, you may want to handle it differently than the standard way. The exception can be thrown again in a "catch" block.

The script should hide system errors from the user. System errors may be important to programmers, but users are not interested in them. To make it easier for users, you can throw the exception again with a user-friendly message:
Copy code The code is as follows:

class customException extends Exception { public function errorMessage() {
//error message
$errorMsg = $this->getMessage().' is not a valid E-Mail address.'; return $errorMsg; } }$email = “someone@example.com”;try { try {
//check for “example” in mail address
if(strpos($email , “example”) !== FALSE) {
//throw exception if email is not valid throw new
Exception($email); } } catch(Exception $e) {
//re- throw exception throw new
customException($email); } }catch (customException $e) {
//display custom message
echo $e->errorMessage(); }
?>

Explanation of the example:
The above code detects whether the email address contains the string "example". If so, throw the exception again:

The customException() class was created as an extension of the old exception class. This way it inherits all properties and methods of the old class.
Create errorMessage() function. If the e-mail address is not valid, this function returns an error message.
Set the $email variable to a valid email address, but containing the string "example".
A "try" block contains another "try" block so that the exception can be thrown again.
The exception is triggered because the e-mail contains the string "example".
"catch" catches the exception and rethrows "customException".
Caught "customException" and displays an error message.
If the exception is not caught in its current "try" block, it will look for a catch block at a higher level.
Set Top Level Exception Handler
The set_exception_handler() function can set a user-defined function that handles all uncaught exceptions.
Copy code The code is as follows:

function myException($exception){
echo "Exception: " , $exception->getMessage();
}
set_exception_handler('myException');
throw new Exception('Uncaught Exception occurred') ;
?>

The output of the above code should be similar to this:

Exception: Uncaught Exception occurred
In the above code, there is no "catch" code block, triggering the top-level exception handler instead. This function should be used to catch all uncaught exceptions.
Exception rules
Code that requires exception handling should be placed within a try block to catch potential exceptions.
Each try or throw block must have at least one corresponding catch block.
Use multiple catch blocks to catch different kinds of exceptions.
Exceptions can be re-thrown in a catch block within a try block.
In short: if an exception is thrown, you must catch it.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/322889.htmlTechArticleFirst of all, you need to know what is a PHP exception? Exceptions are used to change the normal flow of a script when a specified error occurs. PHP 5 provides a new object-oriented approach to error handling. ...
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

In this chapter, we are going to learn the following topics related to routing ?

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

See all articles