目的:想要使用try...catch捕獲不同的異常
eg1:
<?php //創建三個Exception class AException extends Exception{ function printMsg(){ echo "This is AException."; } } class BException extends Exception{ function printMsg(){ echo "This is BException."; } }class CException extends Exception{ function printMsg(){ echo "This is CException."; } } //一個try,多個catch捕獲不同的異常 try{ $flag = 1; switch ($flag) { case 1: throw new AException('AException:'); break; case 2: throw new BException('BException:'); break; case 3: throw new CException('CException:'); break; default: break; } } catch(AException $e){ echo $e->getmessage(); $e->printMsg(); } catch(BException $e){ echo $e->getmessage(); $e->printMsg(); } catch(CException $e){ echo $e->getmessage(); $e->printMsg(); } catch(Exception $e){ //這個catch主要是捕獲漏網之魚 echo $e->getmessage(); }
輸出:
AException:This is AException.
eg2:
使用了PHP的新特性,一個catch語句塊現在可以通過管道字符(|)來實現多個異常的捕獲。 這對於需要同時處理來自不同類的不同異常時很有用
try { // some code } catch (FirstException | SecondException $e) { // handle first and second exceptions if ($e instanceof FirstException ) { .... } .... } catch (\Exception $e) { // ... } finally{ // }