php中的抛出异常和捕捉特定类型的异常

版权声明:此文章转载自_infocool

原文链接:http://www.infocool.net/kb/PHP/201610/204489.html

如需转载请联系听云College团队成员小尹 邮箱:yinhy#tingyun.com

测试环境:PHP5.5.36  Safari 9.1.2 

异常捕获,在现在很多ide工具里都可以用快捷键很方便的添加上,防止用户看到自己看不懂的报错甚至莫名其妙崩溃,导致用户体验不好。

哪怕显示一个友好一些的崩溃提示,也比直接显示error:xxxx xxxxxxxxx要好得多。

当然最终的目的还是要给出对应的解决办法,让代码可以继续运行。

 1 <?php
 2 header("content-type:text/html; charset=utf-8");
 3 /**
 4  * 包裹重量异常
 5  */
 6 class HeavyParcelException extends Exception {}
 7 
 8 /**
 9  * 包裹类
10  */
11 class Parcel {
12 
13         /**
14          * 包裹寄送目的地地址
15          */
16         public $address;
17 
18         /**
19          * 包裹重量
20          */
21         public $weight;
22 }
23 
24 /**
25  * 派送员
26  */
27 class Courier {
28     
29         /** 
30          * 运送
31          */
32         public function ship(Parcel $parcel) {
33                 //check we have an address
34                 //如果包裹的目的地为空
35                 if(empty($parcel->address)) {
36                         throw new Exception('address not Specified(未填写地址)!');
37                 }   
38 
39                 //check the weight
40                 //如果重量超过5
41                 if($parcel->weight > 5) {
42                         throw new HeavyParcelException('Parcel exceeds courier limit(包裹超过运送上限)!');
43                 }   
44 
45                 //otherwise we're coll
46                 return true;
47         }
48 }
49 
50 $myCourier = new Courier();
51 $parcel = new Parcel();
52 //add the address if we have it 为了测试这里不填写地址
53 $parcel->weight = 7;
54 try {
55         $myCourier->ship($parcel);
56         echo "parcel shipped";
57 } catch (HeavyParcelException $e) {//捕获HeavyParcelException 不写这个异常的类型名字,就跑到普通Exception抛出去了
58         echo "Parcel weight error(重量错误): " . $e->getMessage();
59         //redirect them to choose another courier
60 } catch (Exception $e) {
61         echo "Someting went wrong(地址错误): " . $e->getMessage();
62         //exit so we don't try to proceed any further
63         exit;
64 }
65 echo '<br/>';
66 $a = 123;
67 echo $a;

从54行开始的代码执行顺序:

55 >

32 >

35(ship方法中先检查的是地址为空,这里会抛出Exception,而非57行的HeavyParcelException) >

60(捕获到Exception) >

616263 输出地址错误 exit;不会输出65到67行了

--------------------------------------

Tips:

我感觉这一块最重要的就是搞清楚代码执行的顺序。写几段,然后改一改跑一跑。

1.捕获的顺序,要看try中的代码中throw的是哪个类型的Exception,然后才看 catch里的顺序。

2.57行的捕获的是特定的类型HeavyParcelException不能写错,或写Exception都会有问题。可以自己试试。

1)例如地址不为空,57行写成了HeavyParcelException111,就会,在60行它的父类对象中捕获到,重量错误。这不是我们想要的。

2)例如地址为空,57行写成了Exception,会抛出地址错误,但捕获的却是本来负责重量的catch。这也不是我们想要的。


想阅读更多技术文章,请访问听云技术博客,访问听云官方网站感受更多应用性能优化魔力。

关于作者

coco秋洁

我爱学习,学习使我快乐

我要评论

评论请先登录,或注册