Try catch catch exception instance in PHP detailed _php tips

Source: Internet
Author: User
Tags getmessage try catch

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

Try catch in PHP can help us catch the exception of the program code, so that we can deal with some unnecessary errors, interested friends can take a look.

Overview of try{}catch{} statements in PHP

PHP5 has added an exception-handling module similar to other languages. The exception generated in the PHP code can be thrown by the throw statement and caught by the catch statement. (Note: Must be thrown first to get)

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

Each try must have at least one catch that corresponds to it.

Use multiple catch to catch exceptions generated by different classes.

When a try code block no longer throws an exception or cannot find a catch to match the thrown exception, the PHP code continues after the jump 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 that follows (the code block where the exception was thrown) will not continue, and PHP will try to find the first catch that matches it.

If an exception is not captured, and does not use Set_exception_handler () for the corresponding processing, then PHP will produce a serious error, and output uncaught exception ... (Exception not caught) message.

Let's take a look at the basic properties and methods of the PHP built-in exception class. (does not include specific implementations)

Copy Code code as follows:
try{
}
catch () {
throw new Exception ();
}
catch () {
Here you can capture the exception thrown in front of a block
}

To further handle the exception, we need to use the PHP try{}catch{}----include the try statement and at least one of the catch statements. Any code that invokes a method that might throw an exception should use a try statement. Catch statements are used to handle exceptions that may be thrown. Here's how we handle the exception thrown by Getcommandobject ():

Copy 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 using the Throw keyword in conjunction with PHP try{}catch{}, we can avoid the error marking the value returned by the "pollution" class method. Because "exception" itself is a type of PHP that is different 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 moves to the script in the catch statement.

Examples are as follows:

Include file error throwing exception

Copy Code code as follows:
<?php
Wrong demo
try {
Require (' test_try_catch.php ');
catch (Exception $e) {
echo $e->getmessage ();
}

Throw the 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 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 you have more than one catch code block, the object passed to each catch code block must have different types so that PHP can find which catch code block you need to enter. When a try code block no longer throws an exception or cannot find a catch to match the thrown exception, the PHP code continues after the last catch of the jump. Examples of capture of multiple exceptions are as follows:

Copy Code code as follows:
<?php
Class MyException extends exception{
Redefine the constructor so that the first argument 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 that you call Parent::construct () at the same time to check that all variables have been assigned
Parent::__construct ($message, $code);
}
Overrides the inherited method in the parent class, customizing the style of the string output
Public Function __tostring () {
Return __class__. ": [". $this->code. "]:". $this->message. " <br> ";
}
Customize a processing method for this exception
Public Function customfunction () {
echo "handles this type of exception that appears in a custom Way";
}
}

Create an exception class to test the custom extension myexception
Class testexception{
Public $var; Used to determine whether an object creates a successful member property
function __construct ($value =0) {//The exception that is thrown is determined by the pass value of the constructor method
Switch ($value) {//Make a selective judgment of the values passed in
Case 1://mixed with parameter 1, the custom exception object is thrown
throw new MyException ("Incoming value" 1 "is an invalid parameter", 5);
Case 2://Incoming parameter 2 throws the exception object built into PHP
throw new MyException ("Incoming value" 2 "is not allowed as an argument", 6);
Default://Incoming argument is valid, no exception thrown
$this->var= $value; Assigning values to member properties in an object
}
}
}

Example 1, when there is no exception, the program executes normally, and all the code in a try executes without executing any catch blocks
try{
$TESTOBJ =new testexception (); Use default parameters to create an exception's Wipe class object
echo "********<br>"; This statement will execute correctly without throwing an exception
}catch (myexception $e) {//capture user-defined exception blocks
Echo captures a custom exception: $e <br>; Output an exception message in a customized way
$e->customfunction (); You can call a custom exception-handling method
}catch (Exception $e) {//Capture object of PHP's built-in exception handling class
echo "captures the default exception:". $e->getmessage ().       <br> "; Output Exception message
}
Var_dump ($TESTOBJ); Determines whether the object was created successfully and, if there are no exceptions, creates a successful

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

Example 2, thrown from the built-in exception, catches the exception through a custom exception-handling class and processes the
try{
$TESTOBJ 2 =new testexception (2); Pass in 2 o'clock, throw the built-in exception
echo "********<br>"; This statement will not be executed
}catch (myexception $e) {//The code in this catch block will be executed
Echo captures a custom exception: $e <br>;
$e->customfunction ();
}catch (Exception $e) {//This catch block does not execute
echo "captures the default exception:". $e->getmessage (). <br> ";
}
Var_dump ($TESTOBJ 2); Exception generated, 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 a built-in exception-handling class exception in PHP. The object of the test class testexception is created in the try block, and the custom exception class object, the built-in exception class object, and no exception thrown, are thrown into the corresponding catch block according to the different numeric parameters provided in the constructor method. If no exception occurs, the execution is not entered in any of the catch blocks, and the test class TestException object is created successfully

I hope this article will help you with your PHP program design.

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.