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

时间:2023-03-08 20:43:16
测试环境:PHP5.5.36  Safari 9.1.2
异常捕获,在现在很多ide工具里都可以用快捷键很方便的添加上,防止用户看到自己看不懂的报错甚至莫名其妙崩溃,导致用户体验不好。
哪怕显示一个友好一些的崩溃提示,也比直接显示error:xxxx xxxxxxxxx要好得多。
当然最终的目的还是要给出对应的解决办法,让代码可以继续运行。
 <?php
header("content-type:text/html; charset=utf-8");
/**
* 包裹重量异常
*/
class HeavyParcelException extends Exception {} /**
* 包裹类
*/
class Parcel { /**
* 包裹寄送目的地地址
*/
public $address; /**
* 包裹重量
*/
public $weight;
} /**
* 派送员
*/
class Courier { /**
* 运送
*/
public function ship(Parcel $parcel) {
//check we have an address
//如果包裹的目的地为空
if(empty($parcel->address)) {
throw new Exception('address not Specified(未填写地址)!');
} //check the weight
//如果重量超过5
if($parcel->weight > 5) {
throw new HeavyParcelException('Parcel exceeds courier limit(包裹超过运送上限)!');
} //otherwise we're coll
return true;
}
} $myCourier = new Courier();
$parcel = new Parcel();
//add the address if we have it 为了测试这里不填写地址
$parcel->weight = 7;
try {
$myCourier->ship($parcel);
echo "parcel shipped";
} catch (HeavyParcelException $e) {//捕获HeavyParcelException 不写这个异常的类型名字,就跑到普通Exception抛出去了
echo "Parcel weight error(重量错误): " . $e->getMessage();
//redirect them to choose another courier
} catch (Exception $e) {
echo "Someting went wrong(地址错误): " . $e->getMessage();
//exit so we don't try to proceed any further
exit;
}
echo '<br/>';
$a = 123;
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。这也不是我们想要的。