PHP 巢狀異常


簡介

try - catch 塊可以巢狀到任何所需的級別。異常將按出現順序的倒序列進行處理,即最內部異常處理最先完成。

示例

在以下示例中,內部 try 塊會檢查兩個變數是否是數字,如果不是,則丟擲使用者自定義異常。外部 try 塊如果分母為 0,則丟擲 DivisionByZeroError。否則將顯示兩個數字的除法。

示例

 線上演示

<?php
class myException extends Exception{
   function message(){
      return "error : " . $this->getMessage() . " in line no " . $this->getLine();
   }
}
$x=10;
$y=0;
try{
   if (is_numeric($x)==FALSE || is_numeric($y)==FALSE)
      throw new myException("Non numeric data");
}
catch (myException $m){
   echo $m->message();
   return;
}
if ($y==0)
   throw new DivisionByZeroError ("Division by 0");
echo $x/$y;
}
catch (DivisionByZeroError $e){
   echo $e->getMessage() ."in line no " . $e->getLine();
}
?>

輸出

顯示以下輸出

Division by 0 in line no 19

將任何一個變數更改為非數字值

error : Non numeric data in line no 20

如果兩個變數都是數字,則會列印它們的除法

更新於: 2020-09-18

518 次瀏覽

開啟您的 職業

完成課程並獲得認證

開始學習
廣告
© . All rights reserved.