Detailed description of trycatch catch exception instance in php, trycatch_PHP tutorial

Source: Internet
Author: User
Detailed description of trycatch catch exception instances in php. Detailed description of trycatch catch exception examples in php. trycatch this article describes the trycatch catch exception in php. Share it with you for your reference. The specific method analysis is as follows: In php, trycatch can catch exceptions in php by using try catch.

This article describes how to catch exceptions in php. Share it with you for your reference. The specific method is analyzed as follows:

Try catch in php can help us capture program code exceptions, so that we can handle unnecessary errors well. interested friends can take a look at it together.

Overview of try {} catch {} statements in PHP

PHP5 adds exception handling modules similar to other languages. Exceptions in PHP code can be thrown by throw statements and captured by catch statements. (Note: you must first throw it to obtain it)

All codes that require exception handling must be placed in the try code block to capture possible exceptions.

Each try must have at least one catch corresponding to it.

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 another throw exception to be thrown in the catch code block.

When an exception is thrown, subsequent code (the code block where the exception is thrown) will not continue to be executed, 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 specific implementations)

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. Catch statements are used to handle exceptions that may be thrown. The following shows how to handle the Exception thrown by getCommandObject:

The code is as follows:

<? Php
Try {
$ Mgr = new CommandManager ();
$ Cmd = $ mgr-> getCommandObject ("realcommand ");
$ Cmd-> execute ();
} Catch (Exception $ e ){
Print $ e-> getMessage ();
Exit ();
}
?>


As you can see, by combining the throw keyword with try {} catch {} in PHP, we can avoid the error of marking the value returned by the "pollution" class method. "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.

Example:

An exception is thrown when a file inclusion error occurs.

The code is as follows:

<? Php
// Incorrect demo
Try {
Require ('test _ try_catch.php ');
} Catch (Exception $ e ){
Echo $ e-> 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 code 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:

The code is as follows:

<? Php
Class MyException extends Exception {
// Redefine the constructor to change the first parameter message to a required attribute
Public function _ construct ($ message, $ code = 0 ){
// Some codes can be defined here
// We recommend that you call parent: construct () to check whether all variables have been assigned values.
Parent: :__ construct ($ message, $ code );
}
// Override the methods inherited from the parent class and customize the output style of the string
Public function _ toString (){
Return _ CLASS _. ": [". $ this-> code. "]:". $ this-> message ."
";
}
// Customize a processing method for this exception
Public function customFunction (){
Echo "handling exceptions of this type by custom method ";
}
}

// Create an exception class MyException for testing custom extensions
Class TestException {
Public $ var; // The member attribute used to determine whether an object is successfully created.
Function _ construct ($ value = 0) {// The Exception thrown by passing the value of the constructor
Switch ($ value) {// select the input value
Case 1: // If parameter 1 is added, a custom exception object is thrown.
Throw new MyException ("the input value" 1 "is an invalid parameter", 5); break;
Case 2: // If parameter 2 is input, the PHP built-in exception object is thrown.
Throw new MyException ("the 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; // assign values to the member attributes 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 user-defined exception blocks
Echo "capture custom exceptions: $ e
"; // Output exception messages in custom mode
$ E-> customFunction (); // you can call a custom exception handling method.
} Catch (Exception $ e) {// catch the object of the PHP built-in Exception handling class
Echo "capture default exceptions:". $ e-> getMessage ()."
"; // Output an 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 and capture and handle the exception through the custom exception handling class
Try {
$ TestObj1 = new TestException (1); // when 1 is passed, 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 "capture custom exceptions: $ e
";
$ E-> customFunction ();
} Catch (Exception $ e) {// This catch block will not be executed
Echo "capture default exceptions:". $ 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 2 is passed in, a built-in exception is thrown.
Echo "********
"; // This statement will not be executed
} Catch (MyException $ e) {// The code in this catch block will be executed
Echo "capture custom exceptions: $ e
";
$ E-> customFunction ();
} Catch (Exception $ e) {// This catch block will not be executed
Echo "capture default exceptions:". $ 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 created successfully.

I hope this article will help you with php programming.

Examples of catch exceptions are described in detail. trycatch this article describes how to catch exceptions in php. Share it with you for your reference. The specific method analysis is as follows: php can try catch...

Related Article

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.