帶有多個 catch 塊的 PHP 異常處理


簡介

PHP 允許在 try 塊後面使用一系列 catch 塊來處理不同的異常情況。各種 catch 塊可用於處理預定義的異常和錯誤,以及使用者定義的異常。

示例

以下示例使用 catch 塊來處理 DivisioByZeroError、TypeError、ArgumentCountError 和 InvalidArgumentException 條件。還有一個 catch 塊用於處理一般的 Exception 情況。

示例

 現場演示

<?php
declare(strict_types=1);
function divide(int $a, int $b) : int {
   return $a / $b;
}
$a=10;
$b=0;
try{
   if (!$b) {
      throw new DivisionByZeroError('Division by zero.');}
      if (is_int($a)==FALSE || is_int($b)==FALSE)
         throw new InvalidArgumentException("Invalid type of arguments");
         $result=divide($a, $b);
         echo $result;
      }
      catch (TypeError $x)//if argument types not matching{
         echo $x->getMessage();
   }
   catch (DivisionByZeroError $y) //if denominator is 0{
      echo $y->getMessage();
}
catch (ArgumentCountError $z) //if no.of arguments not equal to 2{
   echo $z->getMessage();
}
catch (InvalidArgumentException $i) //if argument types not matching{
   echo $i->getMessage();
}
catch (Exception $ex) // any uncaught exception{
   echo $ex->getMessage();
}
?>

輸出

首先,由於分母為 0,因此會顯示除以 0 錯誤

Division by 0

將 $b 設定為 3,這將導致 TypeError,因為 divide 函式預期返回整數,但除法結果為浮點數

Return value of divide() must be of the type integer, float returned

如果透過更改 $res=divide($a); 只向 divide 函式傳遞一個變數,這將導致 ArgumentCountError

Too few arguments to function divide(), 1 passed in C:\xampp\php\test1.php on line 13 and exactly 2 expected

如果其中一個引數不是整數,則為 InvalidArgumentException 的情況

Invalid type of arguments

更新於:2020 年 9 月 18 日

1K+ 瀏覽次數

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告