php抛出异常与捕捉特定类型的异常详解

2018-09-20 23:44

阅读:357

  什么是异常?

  PHP 5 提供了一种新的面向对象的错误处理方法。

  异常处理用于在指定的错误(异常)情况发生时改变脚本的正常流程。这种情况称为异常。

  当异常被触发时,通常会发生:

   当前代码状态被保存

   代码执行被切换到预定义的异常处理器函数

   根据情况,处理器也许会从保存的代码状态重新开始执行代码,终止脚本执行,或从代码中另外的位置继续执行脚本

  我们将展示不同的错误处理方法:

   异常的基本使用

   创建自定义的异常处理器

   多个异常

   重新抛出异常

   设置顶层异常处理器

  php抛出异常与捕捉特定类型的异常最终的目的还是要给出对应的解决办法,让代码可以继续运行。

  本文的测试环境:PHP5.5.36 Safari 9.1.2

   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 were 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 dont 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。这也不是我们想要的。

  总结

  以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。


评论


亲,登录后才可以留言!