An Exception is an error-handling mechanism that alters the normal flow of a script when a specified error occurs.

When an exception is raised, the current code state is saved and code execution is switched to a predefined exception handler function (if any)

Depending on the situation, the processor may restart code execution from the saved code state, terminate script execution, or resume script execution from another location in the code

When an exception is thrown, subsequent code does not continue to execute. PHP attempts to find a matching “catch” block of code.

If the Exception is not caught and is not handled with set_Exception_handler (), a serious error (fatal) will occur and an “Uncaught Exception” error message will be printed.

Try to throw an exception without catching it

//create function with an exception
function checkNum($number){
    if($number>1) {throw new Exception("Value must be 1 or below"); }}//trigger exception
checkNum(2);
Copy the code

The above code gets an error like this:

Fatal error: Uncaught exception 'Exception' with message 'Value must be 1 or below' in C:\webfolder\test.php:6
Copy the code
Stack trace: #0 C:\webfolder\test.php(12):checkNum(28) #1 {main} thrown in C:\webfolder\test.php on line 6
Copy the code

Note: PHP defaults to warning mode. If you need to use exception handling for system errors, set error handling mode before handling code

set_error_handler(function(){
    throw new Exception('wrong! ');
});
Copy the code

3. The correct handlers should include:

Try – Functions that use exceptions should be inside the “Try” code block. If no exception is raised, the code continues as usual. But if an exception is raised, an exception is thrown.

Throw – This specifies how an exception is raised. Every throw must correspond to at least one catch.

Catch – The “Catch” code block catches the exception and creates an object containing the exception information

// Create a function that throws an exception
function checkNum($number){
    if($number>1) {throw new Exception("Value must be 1 or below"); }}// Raise an exception in the "try" block
try{
    checkNum(2);
}catch(Exception $e) { // Catch an exception
    echo 'File: '.$e->getFile().' line: '.$e->getLine().'<br>';
    die('Message: '.$e->getMessage());
}
Copy the code

The above code will get an error like this:

File: E:\webdev\www\pdo\3.php line: 7
Message: Value must be 1 or below
Copy the code

Code parsing: Create the checkNum() function. It detects if the number is greater than 1. If so, an exception is thrown. CheckNum () is called in the “try” block. An exception is thrown in the checkNum() function. The “catch” block receives the exception and creates an object ($e) containing the exception information. Output an error message from the exception object

However, to follow the “catch for every throw” principle, you can set up a top-level exception handler to handle missed errors, as shown in point 7

The handler creates a special class whose function can be called when an exception occurs in PHP. The class must be an extension of the Exception class. This custom Exception class inherits all the attributes of PHP’s Exception class, to which you can add custom functions.

class customException extends Exception{
    public function errorMessage(){
        return 'Error on line '.$this->getLine().' in '.$this->getFile().': <b>'.$this->getMessage().'</b> is not a valid E-Mail address'; }}$email = "someone@example... com";
try{
    // Use a PHP filter to validate the mailbox
    if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {throw new customException($email); }}catch (customException $e) {echo $e->errorMessage();
}
Copy the code

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

The above code throws an exception and catches it with a custom Exception class: create the errorMessage() function. If the E-mail address is invalid, the function returns an error message

Multiple exception capture can use multiple exceptions for a script to detect multiple situations.

You can use multiple if.. Else code block, or a switch code block, or nested multiple exceptions. These exceptions can use different Exception classes and return different error messages:

class customException extends Exception{
    public function errorMessage(){
        return = 'Error on line '.$this->getLine().' in '.$this->getFile().': <b>'.$this->getMessage().'</b> is not a valid E-Mail address'; }}$email = "[email protected]";
try{
    if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {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();
}
Copy the code

The above code tests two conditions. If neither condition is true, an exception is thrown:

Execute the “try” block. In the first condition, no exception is thrown. Since the E-mail contains the string “example”, the second condition raises an exception. The catch” code block catches the exception and displays the appropriate error message, and if no customException is caught, only a Base Exception is caught, then the exception is handled there.

Sometimes, when an exception is thrown, you might want to handle it in a different way than the standard. You can throw an exception again in a “catch” code block. Scripts should hide system errors from users. System bugs may be important to programmers, but they are not of interest to users. To make it easier for users to use, we can throw an exception again with a more user-friendly message:

class customException extends Exception{
    public function errorMessage(){
        return $this->getMessage().' is not a valid E-Mail address.'; }}$email = "[email protected]";
try{
    try{
        if(strpos($email."example")! = =FALSE) {throw new Exception($email); }}catch(Exception $e) {//re-throw exception
        throw new customException($email); }}catch (customException $e) {//display custom message
    echo $e->errorMessage();
}
Copy the code

The above code checks if the mail address contains the string “example”. If so, throw an exception again:

Set the $email variable to a valid email address, but with the string “example”. The try” block contains another “try” block so that the exception can be thrown again. An exception is raised because the E-mail contains the string “example”. Catch “catches the exception and rethrows “customException”. “CustomException” is caught and an error message is displayed.

If the exception is not caught in its current “try” block, it looks for the catch block at a higher level.

The set_Exception_handler () function sets the user-defined function to handle all uncaught exceptions

function myException($exception){
    echo "<b>Exception:</b> " , $exception->getMessage();
}
set_exception_handler('myException');
throw new Exception('Uncaught Exception occurred');
Copy the code

The output from the above code should look something like this:

Exception: Uncaught Exception occurred
Copy the code

In the above code, there is no “catch” block. Instead, the top-level exception handler is triggered. You should use this function to catch any exceptions that are not caught. However, an error automatically thrown by the system is handled by set_ERROR_handler and an exception is thrown before it is handled by set_EXCEPtion_handler

function myException($exception){
    echo "<b>Exception:</b> " , $exception->getMessage();
}
set_exception_handler('myException');
set_error_handler(function(){
    throw new Exception('wrong! ');
});
echo 10/0;  // Trigger the warning that the dividend cannot be zero
Copy the code

Code execution result: Exception: error!

The above content hopes to help you, more free PHP factory PDF, PHP advanced architecture video materials, PHP wonderful good article can be wechat search concerns: PHP open source community

2021 Jinsanyin four big factory interview real questions collection, must see!

Four years of PHP technical articles collation collection – PHP framework

A collection of four years’ worth of PHP technical articles – Microservices Architecture

Distributed Architecture is a four-year collection of PHP technical articles

Four years of PHP technical essays – High Concurrency scenarios

Four years of elite PHP technical article collation collection – database