Detailed explanation of try catch catching exception instance in php

  • 2021-08-05 09:28:00
  • OfStack

This article illustrates an try catch catch exception in php. Share it for your reference. Specific methods are analyzed as follows:

php try catch can help us catch the exception of the program code, so that we can deal with some unnecessary errors well, interested friends can take a look at it.

Overview of try {} catch {} Statement in PHP

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

Any code that requires exception handling must be placed in the try code block in order to catch possible exceptions.

Every try must have at least one corresponding catch.

Using multiple catch can 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 continues after jumping to the last catch.

Of course, PHP allows an exception (throw) to be thrown again within the catch code block.

When an exception is thrown, the following code will not continue to execute, and PHP will try to find the first catch that can match it.

If an exception is not caught and is not handled with set_exception_handler (), then PHP will produce a serious error and output an Uncaught Exception... (exception not caught).

First, let's look at the basic properties and methods of PHP built-in exception class under 1. (Excluding implementation)

try{
}
catch(){
throw new Exception();
}
catch(){
// You can capture the front here 1 Throwed by a block Exception
}

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

<?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 mismarking the values returned by "contaminated" class methods. Because "exception" is itself a built-in type of PHP that is different from any other object, there is no confusion.

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

Examples are as follows:

Include file error throws exception

<?php
// Wrong demonstration
try {
require ('test_try_catch.php');
} catch (Exception $e) {
echo $e->getMessage();
} // Throw exceptions 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, an fatal error is generated.

Multiple catch catch multiple exceptions

PHP will query a matching catch code block. If there are multiple catch code blocks, the objects passed to each catch code block must have a different type so that PHP can find out which one catch code block needs to be entered. When the try code block no longer throws an exception or no catch can be found to match the thrown exception, the PHP code continues after jumping to the last catch. Examples of catching multiple exceptions are as follows:

<?php 
    class MyException extends Exception{
           //重定义构造器使第1个参数message变为必须被指定的属性
           public function __construct($message, $code=0){
               //可以在这里定义1些自己的代码
               //建议同时调用parent::construct()来检查所有的变量是否已被赋值
               parent::__construct($message, $code);
           }
           //重写父类中继承过来的方法,自定义字符串输出的样式
           public function __toString(){
               return __CLASS__.":[".$this->code."]:".$this->message."<br>";
           }
           //为这个异常自定义1个处理方法
           public function customFunction(){
               echo "按自定义的方法处理出现的这个类型的异常";
           }
    }
 
    //创建1个用于测试自定义扩展的异常类MyException
    class TestException{
        public $var;           //用来判断对象是否创建成功的成员属性
        function __construct($value=0){              //通过构造方法的传值决定抛出的异常
            switch($value){                          //对传入的值进行选择性的判断
                case 1:                              //掺入参数1,则抛出自定义的异常对象
                    throw new MyException("传入的值“1”是1个无效的参数",5);break;
                case 2:                              //传入参数2,则抛出PHP内置的异常对象
                    throw new MyException("传入的值“2”不允许作为1个参数",6);break;
                default:                             //传入参数合法,则不抛出异常
                    $this->var=$value;break;          //为对象中的成员属性赋值
            }
        }
    }
 
    //示例1,在没有异常时,程序正常执行,try中的代码全部执行并不会执行任何catch区块
    try{
        $testObj =new TestException();           //使用默认参数创建异常的擦拭类对象
        echo "********<br>";                     //没有抛出异常这条语句就会正常执行
    }catch(MyException $e){                      //捕获用户自定义的异常区块
        echo "捕获自定义的异常:$e<br>";          //按自定义的方式输出异常消息
        $e->customFunction();                    //可以调用自定义的异常处理方法
    }catch(Exception $e){                        //捕获PHP内置的异常处理类的对象
        echo "捕获默认的异常:".$e->getMessage()."<br>";       //输出异常消息
    }
    var_dump($testObj);        //判断对象是否创建成功,如果没有任何异常,则创建成功
 
    //示例2,抛出自定义的异常,并通过自定义的异常处理类捕获这个异常并处理
    try{
        $testObj1 =new TestException(1);         //传1时,抛出自定义异常
        echo "********<br>";                     //这个语句不会被执行
    }catch(MyException $e){                      //这个catch区块中的代码将被执行
        echo "捕获自定义的异常:$e<br>";         
        $e->customFunction();                   
    }catch(Exception $e){                        //这个catch区块不会执行
        echo "捕获默认的异常:".$e->getMessage()."<br>";      
    }
    var_dump($testObj1);        //有异常产生,这个对象没有创建成功
 
    //示例2,抛出自内置的异常,并通过自定义的异常处理类捕获这个异常并处理
    try{
        $testObj2 =new TestException(2);         //传入2时,抛出内置异常
        echo "********<br>";                     //这个语句不会被执行
    }catch(MyException $e){                      //这个catch区块中的代码将被执行
        echo "捕获自定义的异常:$e<br>";         
        $e->customFunction();                   
    }catch(Exception $e){                        //这个catch区块不会执行
        echo "捕获默认的异常:".$e->getMessage()."<br>";      
    }
    var_dump($testObj2);        //有异常产生,这个对象没有创建成功
?>

In the above code, you can use two exception handling classes: 1 is the custom exception handling class MyException; The other is the built-in exception handling class Exception in PHP. The objects of test class TestException are created in the try block respectively, and according to the different numeric parameters provided in the construction method, the custom exception class object, the built-in exception class object and the situation of not throwing any exception are thrown, and then jumped to the corresponding catch block for execution. If no exception occurs, it will not be executed in any 1 catch block, and the object of the test class TestException is successfully created

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


Related articles: