萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 異常處理機制全面指南:從基礎到進階實戰

PHP 異常處理體系深度解析

異常處理是現代 PHP 應用健壯性的基石。本文系統講解 PHP 異常類體系、捕獲機制、自定義異常、全局處理器、finally 塊等核心知識,並提供生產級最佳實踐。

內置異常類體系

PHP 預定義兩大核心異常類:

Exception 基類

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 - 錯誤轉異常

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
}

四種異常捕獲策略

1. try-catch 塊 - 基礎捕獲

<?php
try {
    throw new Exception('exception test 1', 1001);
} catch (Exception $e) {
    echo $e->getMessage() . '-' . $e->getCode(); // exception test 1-1001
}
?>

2. set_exception_handler - 全局兜底

<?php
function exception_handler($e) {
    echo "Uncaught exception: " . $e->getMessage() . "\n";
}
set_exception_handler('exception_handler');

throw new Exception('Uncaught Exception');
echo "這行不會執行了"; // 程序終止
?>

關鍵差異:全局處理器捕獲後程序終止,try-catch 可繼續執行。

3. 多 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(); // 兜底處理
}
?>

順序原則:子類異常在前,父類異常在後。

4. finally 塊 - 資源釋放保障 (PHP 5.5+)

<?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 而非 ErrorException
  • 生產環境關閉 display_errors,啟用 log_errors
  • 使用 Throwable 接口(PHP 7+)捕獲所有可拋出對象
copyright © 萬盛學電腦網 all rights reserved