Example of trycatch catch exceptions in php

Source: Internet
Author: User
Trycatch in php can help us capture program code exceptions, so that we can handle unnecessary errors well. the following article summarizes some usage examples of capturing exceptions. try {} catch {} statement in PHP. PHP5 added... try catch in php can help us capture program code exceptions, so that we can handle unnecessary errors well. the following article summarizes some usage examples of exception capturing.

Try {} catch {} statement in PHP.

PHP 5 has added an exception handling module similar to other languages. exceptions generated in PHP code can be thrown by throw statements and captured by catch statements. Note that the exception must be thrown before it can be obtained.

Code that requires exception handling must be placed in the try code block to capture possible exceptions. each try must have at least one catch.

Multiple catch methods can capture exceptions generated by different classes. when the try code block does not throw an exception or the catch code cannot be found to match the Exception thrown, the PHP code will continue to be executed after the jump to the last catch.

Of course, PHP allows a throw exception to be thrown again in the catch code block. When an exception is thrown, it is later (note: refers to the code block where the exception is thrown) and PHP will try to find the first catch that can match it.

If an Exception is not captured and set_exception_handler () is not used for corresponding processing, PHP will generate a serious error and output the Uncaught Exception... (No exception is captured.

Let's take a look at the basic attributes and methods of PHP built-in exception classes, excluding the specific implementation. the code is as follows:

Try {} catch () {throw new Exception ();} catch () {// The Exception thrown by the previous block can be caught here}

To further handle exceptions, we need to use try {} catch {} in PHP to include Try statements and at least one catch statement, any code that calls a method that may throw an exception should use the try statement. The Catch statement is used to handle the exception that may be thrown. the following shows how we handle the Exception thrown by getCommandObject, the code is as follows:

 getCommandObject("realcommand");    $cmd->execute();    } catch (Exception $e) {    print $e->getMessage();    exit();    }

We can see that by combining the throw keyword with try {} catch {} in PHP, we can avoid marking the value returned by the "pollution" class method by mistake, "exception" is a built-in PHP type that is different from any other object and will not be confused.

If an exception is thrown, the script in the try statement stops execution and immediately redirects to the script in the catch statement.

The following example shows how to throw an exception when a file error occurs. the code is as follows:

 GetMessage () ;}// correctly throw an exception. 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 captured, a fatal error occurs.

Catch multiple exceptions

PHP queries a matching catch code block. if there are multiple catch code blocks, the objects passed to each catch code block must have different types, so that PHP can find the catch code block to be entered, when the try code block does not throw an exception or the catch cannot be found to match the Exception thrown, the PHP code will continue to run after the last catch, the following is an example of how to capture multiple exceptions:

 Code. "]:". $ this-> message ."
";}// Customize a processing method for this exception public function customFunction () {echo" handle this type of exception by custom method ";}} // create an exception class MyException class TestException {public $ var; // The member attribute function _ construct ($ value = 0) used to determine whether an object is successfully created {// The exception switch ($ value) thrown is determined by passing the value of the constructor) {// select the input value. case 1: // add parameter 1, throw custom exception object throw new MyException ("input value \" 1 \ "is an invalid parameter", 5); break; case 2: // If parameter 2 is input, throw the PHP built-in exception object throw new MyException ("input value \" 2 \ "cannot be used as a parameter", 6); break; default: // if the input parameter is valid, no exception is thrown. $ this-> var = $ value; break; // value the member attribute in the object }}}

// Example 1: If no exception occurs, the program runs normally. If all the code in try is executed, no catch block is executed.

Try {$ testObj = new TestException (); // use the default parameter to create an abnormal wiping class object echo "********
"; // If No exception is thrown, this statement will be executed normally} catch (MyException $ e) {// capture the user-defined exception block echo" capture the custom exception: $ e
"; // Output Exception messages in custom mode $ e-> customFunction (); // you can call custom Exception handling methods} catch (Exception $ e) {// capture PHP built-in exception handling class object echo "capture default exception :". $ e-> getMessage ()."
"; // Output exception message} var_dump ($ testObj); // determines whether the object is created successfully. If no exception exists, the object is created successfully. // Example 2, throw a custom exception, capture the exception through the custom exception handling class, and handle try {$ testObj1 = new TestException (1); // when passing 1, throw a custom exception 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 does not execute echo" capture the default Exception :". $ e-> getMessage ()."
";} Var_dump ($ testObj1); // An exception occurs. this object is not created successfully.

// Example 2: throw a self-built exception and capture and handle this exception through the custom exception handling class

Try {$ testObj2 = new TestException (2); // when you pass in 2, a built-in exception echo "******** is thrown "********
"; // 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 does not execute echo" capture the default Exception :". $ e-> getMessage ()."
";} Var_dump ($ testObj2); // An exception occurs. this object is not created successfully.

In the above code, two Exception handling classes can be used: one is the custom Exception handling class MyException, and the other is the built-in Exception handling class Exception in PHP, create TestException-like objects in the try block, and create different numeric parameters according to the constructor, when a custom exception class object, built-in exception class object, and no exception are thrown, the system jumps to the corresponding catch block for execution. If no exception occurs, it will not be executed in any catch block. the TestException-like object is successfully created.


Tutorial address:

Reprinted! But please include the article address ^

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.