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。這也不是我們想要的。