Z
ZHANK
编程在线教程PHP 教程错误与异常处理
进阶技巧

错误与异常处理

try/catch/finally、Exception 类、自定义异常、error_reporting

错误与异常处理

PHP 从 7.0 开始,大多数错误都抛出了异常。现代 PHP 错误处理的核心是 try/catch/finally。

学完本章你将: 掌握 try/catch/finally、Exception 类、自定义异常。


try / catch / finally

php
<?php
function divide(float $a, float $b): float {
    if ($b === 0.0) {
        throw new InvalidArgumentException("除数不能为零");
    }
    return $a / $b;
}

try {
    $result = divide(10, 0);
    echo "结果:$result";
} catch (InvalidArgumentException $e) {
    echo "参数错误:" . $e->getMessage();
} catch (Throwable $e) {
    echo "其他错误:" . $e->getMessage();
} finally {
    echo "\n无论是否异常,finally 都会执行";
}

Exception 类层次

Throwable (PHP 7+)
 ├── Error          —— 致命错误(PHP 7+)
 │    ├── TypeError
 │    ├── ParseError
 │    └── ...
 └── Exception      —— 可捕获的异常
      ├── LogicException
      ├── RuntimeException
      └── PDOException

自定义异常

php
<?php
class ValidationException extends Exception {
    public function __construct(
        string $message,
        private readonly array $errors = [],
    ) {
        parent::__construct($message);
    }

    public function getErrors(): array {
        return $this->errors;
    }
}

// 使用
if (empty($name)) {
    throw new ValidationException("验证失败", ["name" => "姓名不能为空"]);
}

全局异常处理

php
<?php
// 捕获所有未处理的异常(适合记录日志/返回友好页面)
set_exception_handler(function (Throwable $e) {
    error_log($e->getMessage());
    http_response_code(500);
    echo "服务器出错了,请稍后再试";
});