PHP 5.5 以後增加 finally ,這是所有 catch 進行完一定會被執行的部份。
舉例如下
<?php
function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
else return 1/$x;
}
try {
echo inverse(5) . "\n";
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
echo 'After ...';
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:try01.php
功能:示範 PHP 程式
作者:張凱慶
時間:西元 2013 年 2 月 */
?>錯誤發生的地方就用 throw 丟出例外物件 (object)
throw new Exception('Division by zero.');有可能發生錯誤的地方就用 try 後面接大括弧圍起來,然後用 catch 捕捉例外物件,底下的大括弧為例外發生後處理的程式
try {
echo inverse(5) . "\n";
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}執行結果如下

| 中英文術語對照 | |
|---|---|
| 例外處理 | exception handling |
| 關鍵字 | keyword |
| 物件 | object |
您可以繼續參考
例外
相關目錄
回 PHP 快速導覽
回 PHP 教材
回首頁
參考資料
http://www.php.net/manual/en/language.exceptions.php
沒有留言:
張貼留言