異常處理是編寫健壯 PHP 應用的關鍵。本文系統整理了 try-catch 基礎用法、自定義異常類、全域異常處理器、異常資訊獲取、多重 catch 區塊順序、異常重拋等核心知識點,並提供完整可執行程式碼範例。
使用 try 區塊包裹可能拋出異常的程式碼,catch 捕獲並處理:
<?php
$path = "D://in.txt";
try {
file_open($path);
} catch(Exception $e) {
echo $e->getMessage();
}
function file_open($path) {
if(!file_exists($path)) {
throw new Exception("檔案無法找到", 1);
}
if(!fopen($path, "r")) {
throw new Exception("檔案無法開啟", 2);
}
}
?>
使用 set_exception_handler() 註冊全域處理函數,捕獲未被 catch 的異常:
<?php
function exception_handler($e) {
echo "未捕獲的異常:" . $e->getMessage();
}
set_exception_handler("exception_handler");
try {
$path = "D://in.txt";
} catch(Exception $e) {
echo $e->getMessage();
}
file_open($path); // 這裡拋出的異常會被全域處理器捕獲
?>
Exception 類提供豐富方法獲取錯誤上下文:
<?php
try {
file_open($path);
} catch(Exception $e) {
echo "異常訊息:" . $e->getMessage() . "\n";
echo "異常代碼:" . $e->getCode() . "\n";
echo "檔案名:" . $e->getFile() . "\n";
echo "行號:" . $e->getLine() . "\n";
echo "堆疊追蹤:\n";
print_r($e->getTrace());
echo $e->getTraceAsString();
}
?>
繼承 Exception 建立業務專用異常,配合多重 catch 實現精準處理:
<?php
class FileExistsException extends Exception {}
class FileOpenException extends Exception {}
try {
file_open($path);
} catch(FileExistsException $e) {
echo "請確認檔案位置。\n";
} catch(FileOpenException $e) {
echo "請確認檔案可讀性。\n";
} catch(Exception $e) {
echo "[未知異常] " . $e->getMessage() . "\n";
}
function file_open($path) {
if(!file_exists($path)) {
throw new FileExistsException("檔案無法找到", 1);
}
if(!fopen($path, "r")) {
throw new FileOpenException("檔案無法開啟", 2);
}
}
?>
在底層捕獲後記錄日誌,再拋出讓上層處理:
<?php
function file_open($path) {
try {
if(!file_exists($path)) throw new FileExistsException("檔案無法找到", 1);
if(!fopen($path, "r")) throw new FileOpenException("檔案無法開啟", 2);
} catch(Exception $e) {
echo "file_open 發生異常\n";
throw $e; // 重拋
}
}
?>
Throwable 介面,涵蓋 Error 與 Exception。