PHP 5 引入類似 Java/C# 的例外處理機制,透過 try、catch、throw 關鍵字實現錯誤流程控制。本文詳細說明 Exception 基礎類別、自訂例外與最佳實踐。
try {
// 可能拋出例外的程式碼
$result = riskyOperation();
} catch (ExceptionType1 $e) {
// 處理特定例外
} catch (ExceptionType2 $e) {
// 處理另一種例外
} finally {
// PHP 5.5+ 支援,無論是否發生例外皆會執行
}
Exception {
/* 屬性 */
protected string $message; // 例外訊息
protected int $code; // 例外代碼
protected string $file; // 拋出檔案
protected int $line; // 拋出行號
/* 方法 */
public __construct(string $message = "", int $code = 0, Exception $previous = NULL);
final public getMessage(): string;
final public getPrevious(): Exception;
final public getCode(): int;
final public getFile(): string;
final public getLine(): int;
final public getTrace(): array;
final public getTraceAsString(): string;
public __toString(): string;
final private __clone(): void;
}
function connectToDatabase() {
if (!$link = @mysql_connect("host", "user", "pass", "db")) {
throw new Exception("Could not connect to database.");
}
}
try {
connectToDatabase();
} catch (Exception $e) {
echo $e->getMessage(); // 輸出: Could not connect to database.
}
繼承 Exception 可攜帶額外資訊、記錄日誌等:
class MyException extends Exception {
protected $errorInfo;
public function __construct($message = null, $code = 0) {
$this->errorInfo = '自訂錯誤類別的錯誤資訊';
parent::__construct($message, $code);
}
public function getErrorInfo() {
return $this->errorInfo;
}
public function log($file) {
file_put_contents($file, $this->__toString(), FILE_APPEND);
}
}
function connectToDatabase() {
throw new MyException("ErrorMessage");
}
try {
connectToDatabase();
} catch (MyException $e) {
echo $e->getMessage() . "\n";
echo $e->getErrorInfo();
}
捕捉未被 catch 捕獲的例外,統一記錄日誌或顯示友善頁面:
function exceptionLogger($exception) {
$file = 'ExceptionLog.log';
file_put_contents($file, $exception->__toString(), FILE_APPEND);
}
set_exception_handler('exceptionLogger');
try {
// ...
} catch (Exception $e) {
if ($e->getCode() == 999) {
// 特殊處理
} else {
throw $e; // 向上層傳遞
}
}
code) 分類錯誤,支援多語系訊息對應。Throwable 介面,涵蓋 Error 與 Exception。