PHP中try、catch、finally的执行顺序

今天在看同事写的代码时,发现用了finally,我之前都不知道PHP中有finally,所以搜索了一些相关的知识,并写了代码来验证。

测试代码如下:

执行catch:

 1 <?php
 2 
 3 $t = new TTT();
 4 echo $t->run(), PHP_EOL;
 5 
 6 class TTT
 7 {
 8     public function run()
 9     {
10         try {
11             echo 'In Try', PHP_EOL;
12             throw new Exception('wrong');
13 
14             return 'From Try';
15         } catch (Exception $e) {
16             echo 'In Catch', PHP_EOL;
17 
18             return 'From Catch';
19         } finally {
20             echo 'In Finally', PHP_EOL;
21 
22             return 'From Finally';
23         }
24     }
25 }

执行结果如下:

没有执行catch: 

 1 <?php
 2 
 3 $t = new TTT();
 4 echo $t->run(), PHP_EOL;
 5 
 6 class TTT
 7 {
 8     public function run()
 9     {
10         try {
11             echo 'In Try', PHP_EOL;
12 //            throw new Exception('wrong');
13 
14             return 'From Try';
15         } catch (Exception $e) {
16             echo 'In Catch', PHP_EOL;
17 
18             return 'From Catch';
19         } finally {
20             echo 'In Finally', PHP_EOL;
21 
22             return 'From Finally';
23         }
24     }
25 }

执行结果:

finally中没有返回值:

 1 <?php
 2 
 3 $t = new TTT();
 4 echo $t->run(), PHP_EOL;
 5 
 6 class TTT
 7 {
 8     public function run()
 9     {
10         try {
11             echo 'In Try', PHP_EOL;
12 //            throw new Exception('wrong');
13 
14             return 'From Try';
15         } catch (Exception $e) {
16             echo 'In Catch', PHP_EOL;
17 
18             return 'From Catch';
19         } finally {
20             echo 'In Finally', PHP_EOL;
21 
22 //            return 'From Finally';
23         }
24     }
25 }

执行结果:

代码的执行顺序是:先执行try,抛出异常的话就会运行catch,没有抛出异常的话则不会运行catch,但这两种情况都会finally,并且,finally中的返回值会覆盖掉前面语句的返回值。

 finally的意义在于可以处理一些资源的清理和回收等操作。

猜你喜欢

转载自www.cnblogs.com/moxiaoping/p/9037534.html