PHP Try catch catch Exception instance detailed, trycatch_php tutorial

Source: Internet
Author: User
Tags getmessage php try catch try catch

Example of a try catch catch exception in PHP, Trycatch


This example describes a try catch catch exception in PHP. Share to everyone for your reference. The specific methods are analyzed as follows:

In PHP, try catch can help us catch the exception of the program code, so we can deal with some unnecessary errors, interested friends can come together to see.

Overview of try{}catch{} statements in PHP

PHP5 adds an exception handling module similar to other languages. Exceptions generated in PHP code can be thrown by a throw statement and captured by a catch statement. (Note: Must be thrown first to obtain)

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

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

You can use multiple catches to catch exceptions that are generated by different classes.

When the try code block no longer throws an exception or cannot find a catch that matches the thrown exception, the PHP code resumes execution after jumping to the last catch.

Of course, PHP allows you to throw (throw) exceptions again within a catch code block.

When an exception is thrown, the code behind it (the code block where the exception was thrown) will not continue, and PHP will attempt to find the first catch to match it.

If an exception is not captured and does not use Set_exception_handler () for the appropriate processing, then PHP will produce a serious error and output uncaught exception ... (The exception is not caught) prompt information.

Let's take a look at the basic properties and methods of the PHP built-in exception class. (not including specific implementations)
Copy the Code code as follows: try{
}
catch () {
throw new Exception ();
}
catch () {
Here you can capture the exception thrown by the previous block
}

To further handle the exception, we need to use PHP try{}catch{}----include a try statement and at least one catch statement. Any code that calls a method that might throw an exception should use a try statement. The catch statement is used to handle the exceptions that may be thrown. The following shows the way we handle exceptions thrown by Getcommandobject ():
Copy the Code code 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 the try{}catch{} in PHP, we can avoid the value returned by the error flag "contaminated" class method. Because "exception" itself is a type of PHP built-in that differs from any other object, it does not create confusion.

If an exception is thrown, the script in the Try statement stops executing and then immediately turns to the script in the Execute Catch statement.

Examples are as follows:

Include file error throwing exception
Copy the Code code as follows: <?php
The wrong demo
try {
Require (' test_try_catch.php ');
} catch (Exception $e) {
echo $e->getmessage ();
}

Correct throwing of exceptions
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 the exception is thrown and is not captured, a fatal error is generated.

Multiple catch captures multiple exceptions

PHP will query for a matching catch code block. If there are multiple catch code blocks, the objects passed to each catch block must have different types so that PHP can find which catch code block to enter. When the try code block no longer throws an exception or the catch can match the thrown exception, the PHP code resumes after the last catch. Examples of the capture of multiple exceptions are as follows:
Copy CodeThe code is as follows: <?php
Class MyException extends exception{
Redefine the constructor so that the first parameter message becomes a property 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 that all variables have been assigned values
Parent::__construct ($message, $code);
}
Overrides the inherited method from the parent class, customizing the style of the string output
Public Function __tostring () {
Return __class__. ": [". $this->code. "]:". $this->message. "
";
}
Customize a processing method for this exception
Public Function customfunction () {
echo "handles the occurrence of this type of exception as a custom method";
}
}

Create an exception class to test the custom extension myexception
Class testexception{
Public $var; The member property used to determine whether the object was created successfully
function __construct ($value =0) {//The thrown exception is determined by the value of the constructor method
Switch ($value) {//Make a selection decision on the value passed in
Case 1://mixed with parameter 1, the custom exception object is thrown
throw new MyException ("Incoming value" 1 "is an invalid argument", 5);
Case 2://Pass in Parameter 2, throw PHP built-in exception object
throw new MyException ("Incoming value" 2 "is not allowed as a parameter", 6);
Default://Incoming argument is valid, no exception is thrown
$this->var= $value; Assigning a value to a member property in an object
}
}
}

Example 1, in the absence of an exception, the program executes normally, and the code in try executes without executing any catch chunks
try{
$TESTOBJ =new testexception (); To create an exception's wipe class object with default parameters
echo "********
"; Without throwing an exception, the statement will execute normally.
}catch (myexception $e) {//capture user-defined exception blocks
Echo captures the custom exception: $e
"; Output exception messages in a customized manner
$e->customfunction (); You can call a custom exception-handling method
}catch (Exception $e) {//Capture objects for PHP built-in exception handling classes
echo "captures the default exception:". $e->getmessage (). "
"; Output Exception message
}
Var_dump ($TESTOBJ); Determines whether the object was created successfully, and if there are no exceptions, the creation succeeds

Example 2, throws a custom exception and catches the exception through a custom exception-handling class and handles
try{
$TESTOBJ 1 =new testexception (1); Pass 1 o'clock, throw a custom exception
echo "********
"; This statement will not be executed
}catch (myexception $e) {//The code in this catch block will be executed
Echo captures the custom exception: $e
";
$e->customfunction ();
}catch (Exception $e) {//This catch block does not execute
echo "captures the default exception:". $e->getmessage (). "
";
}
Var_dump ($TESTOBJ 1); There was an exception, this object was not created successfully

Example 2, throws a self-built exception and catches the exception through a custom exception-handling class and handles
try{
$TESTOBJ 2 =new testexception (2); Incoming 2 o'clock, throws a built-in exception
echo "********
"; This statement will not be executed
}catch (myexception $e) {//The code in this catch block will be executed
Echo captures the custom exception: $e
";
$e->customfunction ();
}catch (Exception $e) {//This catch block does not execute
echo "captures the default exception:". $e->getmessage (). "
";
}
Var_dump ($TESTOBJ 2); There was an exception, this object was not created successfully
?>

In the above code, you can use two exception handling classes: One is a custom exception handling class MyException, and the other is the exception handling class exception built into PHP. A test class TestException object is created in the try block, and a custom exception class object, a built-in exception class object, and no exception are thrown into the corresponding catch block according to the different numeric parameters provided in the construction method. If no exception occurs, it does not go into any one of the catch blocks, and the test class TestException object creation succeeds

I hope this article is helpful to everyone's PHP programming.

http://www.bkjia.com/PHPjc/915425.html www.bkjia.com true http://www.bkjia.com/PHPjc/915425.html techarticle a try catch catch exception instance in PHP is explained in detail, Trycatch This example describes the try catch catch exception in PHP. Share to everyone for your reference. The specific method is analyzed as follows: PHP in the Try catch can ...

  • 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.