PHP catch 關鍵字
示例
捕獲異常
<?php
try {
throw new Exception("這是一個異常");
} catch(Exception $e) {
echo $e->getMessage();
}
?>
自己動手試一試 »
定義和用法
catch
關鍵字用於處理前面 try 塊中丟擲的異常。
相關頁面
throw
關鍵字。
The try
keyword.
The finally
keyword.
在我們的 PHP 異常教程 中閱讀更多關於 try..catch.finally(異常)的內容。
更多示例
示例
使用 catch 處理多種型別的異常
<?php
try {
$rand = rand(0, 2);
switch($rand) {
case 0: throw new Exception();
case 1: throw new OutOfBoundsException();
case 2: throw new LogicException();
}
} catch(OutOfBoundsException $e) {
echo "捕獲了一個越界異常";
} catch(LogicException $e) {
echo "捕獲了一個邏輯異常";
} catch(Exception $e) {
echo "捕獲了一個普通異常";
}
?>
自己動手試一試 »
❮ PHP 關鍵字