Home  >  Article  >  Backend Development  >  Detailed explanation of exception examples captured by try catch in php, trycatch_PHP tutorial

Detailed explanation of exception examples captured by try catch in php, trycatch_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:13:361244browse

Detailed explanation of exception examples captured by try catch in php, trycatch

The example in this article tells about try catch catching exceptions in php. Share it with everyone for your reference. The specific method analysis is as follows:

try catch in php can help us catch exceptions in program code, so that we can handle some unnecessary errors well. Interested friends can take a look.

Overview of try{}catch{} statement in PHP

PHP5 adds an exception handling module similar to other languages. Exceptions generated in PHP code can be thrown by the throw statement and caught by the catch statement. (Note: You must throw it first to get it)

Code that requires exception handling must be placed in a try code block to catch possible exceptions.

Each 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 an exception or no catch can be found to match the thrown exception, the PHP code will continue execution after jumping to the last catch.

Of course, PHP allows exceptions to be thrown again within catch blocks.

When an exception is thrown, the subsequent code (Translator's Note: refers to the code block when the exception is thrown) will not continue to execute, and 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 an Uncaught Exception... (uncaught exception) prompt message.

First, let’s take a look at the basic properties and methods of PHP’s built-in exception class. (excluding specific implementation)

Copy code The code is as follows:
try{
}
catch(){
throw new Exception();
}
catch(){
//Here you can catch the Exception thrown by the previous block
}

In order to further handle the exception, we need to use try{}catch{} in PHP----including Try statement and at least one catch statement. Any code that calls a method that may throw an exception should use a try statement. The Catch statement is used to handle exceptions that may be thrown. The following shows how we handle exceptions thrown by getCommandObject():

Copy code The code is as follows:
try {
$mgr = new CommandManager();
$cmd = $mgr->getCommandObject("realcommand");
$cmd->execute();
} catch (Exception $e) {
print $e->getMessage();
exit();
}
?>

As you can see, by using the throw keyword in conjunction with try{}catch{} in PHP, we can avoid error markers "polluting" the values ​​returned by class methods. Because "exception" itself is a PHP built-in type that is different from any other object, there will be no confusion.

If an exception is thrown, the script in the try statement will stop executing, and then immediately switch to executing the script in the catch statement.

Examples are as follows:

Include file error throws exception

Copy code The code is as follows:
// Wrong demo
try {
require ('test_try_catch.php');
} catch (Exception $e) {
echo $e->getMessage();
}

// Throw exception correctly
try {
if (file_exists('test_try_catch.php')) {
require ('test_try_catch.php');
} else {
throw new Exception('file is not exists');
}
} catch (Exception $e) {
echo $e->getMessage();
}


If an exception is thrown but not caught, a fatal error will occur.

Multiple catches to catch multiple exceptions

PHP will query for a matching catch block. If there are multiple catch blocks, the object passed to each catch block must be of a different type so that PHP can find which catch block it needs to enter. When the try code block no longer throws an exception or no catch can match the thrown exception, the PHP code will continue executing after jumping to the last catch. An example of catching multiple exceptions is as follows:

Copy code The code is as follows:
Class MyException extends Exception{
//Redefine the constructor so that the first parameter message becomes an attribute that must be specified
             public function __construct($message, $code=0){
//You can define some of your own code here
//It is recommended to call parent::construct() at the same time to check whether all variables have been assigned
                  parent ::__construct($message, $code);
           }
//Rewrite the inherited method from the parent class and customize the string output style
             public function __toString(){
                    return __CLASS__.":[".$this->code."]:".$this->message."
";
           }
//Customize a handling method for this exception
             public function customFunction(){
echo "Handle exceptions of this type in a custom way";
           }
}

//Create an exception class MyException
for testing custom extensions Class TestException{
Public $var; //Member attributes used to determine whether the object is successfully created
function __construct($value=0){ //The exception thrown is determined by the value passed in the constructor
                switch($value){                                                                                                                                                                                                                                                                                      Case 1: // Bleast the parameter 1, then throw a custom abnormal object
throw new MyException("The value "1" passed in is an invalid parameter",5);break;
Case 2: // Pass parameter 2, then throw the PHP built -in abnormal object
                                                                                                                                                                                                                               throw new MyException("The value passed in "2" is not allowed as a parameter", 6); break;
Default: // The parameter is legal, but the abnormality is not thrown
                                                                                                                                                               }
}
}

//Example 1, when there is no exception, the program executes normally, all codes in try are executed and no catch block is executed
Try{
$ Testobj = new testxception (); // Use the default parameter to create an abnormal wiping object
echo "********
"; //If no exception is thrown, this statement will be executed normally
} Catch (MyException $ E) {// Capture the user's custom abnormal block
echo "Capture custom exception: $e
"; //Output the exception message in a customized way
                                                                    }catch(Exception $e){                                                                                                                                                                                                                                   // Capture the object of PHP’s built-in exception handling class
echo "Capture the default exception:".$e->getMessage()."
"; //Output exception message
}
var_dump($testObj); //Determine whether the object is created successfully. If there are no exceptions, the creation is successful

//Example 2, throw a custom exception, catch this exception through a custom exception handling class and handle it
Try{
            $testObj1 =new TestException(1);                  //When passing 1, a custom exception is thrown
echo "********
"; //This statement will not be executed
}catch(MyException $e){                                                                                                                                                                                                                    // The code in this catch block will be executed
echo "Catch custom exception: $e
";               $e->customFunction();                            }catch(Exception $e){                                                                                                                                                                                    // This catch block will not be executed
echo "Catch the default exception:".$e->getMessage()."
";
}
var_dump($testObj1); //An exception occurred and this object was not created successfully

//Example 2, throw a built-in exception, catch this exception through a custom exception handling class and handle it
Try{
$ TestObj2 = New Testexception (2); // Pass at 2, throw the built -in abnormalities
echo "********
"; //This statement will not be executed
}catch(MyException $e){                                                                                                                                                                                                                    // The code in this catch block will be executed
echo "Catch custom exception: $e
";               $e->customFunction();                            }catch(Exception $e){                                                                                                                                                                                    // This catch block will not be executed
echo "Catch the default exception:".$e->getMessage()."
";
}
var_dump($testObj2); //An exception occurred and this object was not created successfully
?>

In the above code, you can use two exception handling classes: one is the custom exception handling class MyException; the other is the built-in exception handling class Exception in PHP. Create objects of the test class TestException in the try block respectively, and according to the different numeric parameters provided in the construction method, throw custom exception class objects, built-in exception class objects, and do not throw any exceptions, jump to the corresponding Executed in the catch block. If no exception occurs, it will not enter any catch block for execution, and the object of the test class TestException is successfully created

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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/915425.htmlTechArticleDetailed explanation of try catch exception examples in php, trycatch This article describes the try catch exception example in php. Share it with everyone for your reference. The specific method is analyzed as follows: try catch in php can...
Statement:
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