首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 物件導向程式設計 (OOP) 學習筆記 (四) - 例外處理與 Exception 類別

     編輯:PHP 綜合知識

PHP 5 引入類似 Java/C# 的例外處理機制,透過 try、catch、throw 關鍵字實現錯誤流程控制。本文詳細說明 Exception 基礎類別、自訂例外與最佳實踐。

基本語法結構

try {
    // 可能拋出例外的程式碼
    $result = riskyOperation();
} catch (ExceptionType1 $e) {
    // 處理特定例外
} catch (ExceptionType2 $e) {
    // 處理另一種例外
} finally {
    // PHP 5.5+ 支援,無論是否發生例外皆會執行
}

內建 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 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');

在 catch 中重新拋出例外

try {
    // ...
} catch (Exception $e) {
    if ($e->getCode() == 999) {
        // 特殊處理
    } else {
        throw $e; // 向上層傳遞
    }
}

效能與架構建議

  • 例外僅用於異常情況,不可濫用於一般流程控制 (如驗證失敗)。
  • 大量記錄例外堆疊資訊會影響效能,生產環境建議只記錄關鍵錯誤。
  • 善用例外代碼 (code) 分類錯誤,支援多語系訊息對應。
  • PHP 7+ 可捕捉 Throwable 介面,涵蓋 Error 與 Exception。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved