PHP 5 引入異常機制,try/catch/throw 結構捕獲運行時錯誤。核心類 Exception 提供豐富屬性與方法。
$message、$code、$file、$linegetMessage()、getCode()、getFile()、getLine()、getTrace()、getTraceAsString()、__toString()class MyException extends Exception {
protected $extraInfo;
public function __construct($msg = null, $code = 0) {
$this->extraInfo = '自定義錯誤上下文';
parent::__construct($msg, $code);
}
public function getExtraInfo() { return $this->extraInfo; }
public function log($file) { file_put_contents($file, $this->__toString(), FILE_APPEND); }
}
function ExceptionLogger($e) { file_put_contents('ExceptionLog.log', $e->__toString(), FILE_APPEND); }
set_exception_handler('ExceptionLogger');
catch (Exception $e) {
if ($e->getCode() == 999) { /* 特殊處理 */ }
else { throw $e; } // 向上傳遞
}