異常處理是現代 PHP 應用健壯性的基石。本文系統講解 PHP 異常類體系、捕獲機制、自定義異常、全局處理器、finally 塊等核心知識,並提供生產級最佳實踐。
PHP 預定義兩大核心異常類:
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 getCode(): int
final public getFile(): string
final public getLine(): int
final public getTrace(): array
final public getTraceAsString(): string
public __toString(): string
}
ErrorException extends Exception {
protected int $severity; // 錯誤嚴重級別
public __construct(string $message = "", int $code = 0,
int $severity = 1, string $filename = __FILE__,
int $lineno = __LINE__, Exception $previous = null)
final public getSeverity(): int
}
<?php
try {
throw new Exception('exception test 1', 1001);
} catch (Exception $e) {
echo $e->getMessage() . '-' . $e->getCode(); // exception test 1-1001
}
?>
<?php
function exception_handler($e) {
echo "Uncaught exception: " . $e->getMessage() . "\n";
}
set_exception_handler('exception_handler');
throw new Exception('Uncaught Exception');
echo "這行不會執行了"; // 程序終止
?>
關鍵差異:全局處理器捕獲後程序終止,try-catch 可繼續執行。
<?php
class MyException extends Exception {
public function myFunction() { echo 'just for test'; }
}
try {
throw new MyException('an error');
} catch (MyException $e) {
echo $e->myFunction(); // 處理特定異常
} catch (Exception $e) {
echo $e->getMessage(); // 兜底處理
}
?>
順序原則:子類異常在前,父類異常在後。
<?php
// 傳統模式:資源釋放代碼重複
function doSomething() {
$resource = createResource();
try {
$result = useResource($resource);
} catch (Exception $e) {
releaseResource($resource);
log($e->getMessage());
exit();
}
releaseResource($resource); // 重複代碼
return $result;
}
// finally 模式:資源釋放集中管理
function doSomething2() {
$resource = createResource();
try {
$result = useResource($resource);
return $result;
} catch (Exception $e) {
log($e->getMessage());
exit();
} finally {
releaseResource($resource); // 必定執行
}
}
?>
<?php
try {
// 底層操作
$pdo->query($sql);
} catch (PDOException $e) {
// 轉換為業務異常,隱藏實現細節
throw new RepositoryException('數據查詢失敗', 0, $e);
}
?>
<?php
function logException(Exception $e, string $context = '') {
$log = [
'time' => date('c'),
'message' => $e->getMessage(),
'code' => $e->getCode(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => $e->getTraceAsString(),
'context' => $context
];
error_log(json_encode($log, JSON_UNESCAPED_UNICODE), 3, '/var/log/app/exceptions.log');
}
?>
<?php
function errorToException($severity, $message, $file, $line) {
if (!(error_reporting() & $severity)) return; // 尊重 error_reporting 設置
throw new ErrorException($message, 0, $severity, $file, $line);
}
set_error_handler('errorToException');
?>
Exception 而非 ErrorExceptiondisplay_errors,啟用 log_errorsThrowable 接口(PHP 7+)捕獲所有可拋出對象