PHP Exception
全面核对 PHP 面向对象异常处理机制(try/throw/catch/finally、自定义 Exception 子类、多 catch 分流、异常重抛与 set_exception_handler()),并在 PHP 8.4.27 完成全部实测。
学完这一章,你能够
- 全面核对 PHP 面向对象异常处理机制(try/throw/catch/finally、自定义 Exception 子类、多 catch 分流、异常重抛与 set_exception_handler()),并在 PHP 8.4.27 完成全部实测。
异常概念与基本触发流程
自 PHP 5 引入的面向对象异常处理机制用于在预期之外的错误状态出现时安全改变执行流:触发异常后会保存当前调用状态并将控制权转交至匹配的异常处理器,由处理器决定恢复、转抛或终止脚本。本章涵盖异常基本用法、自定义异常类、多异常分流、重新抛出以及顶层异常处理器五大主题。工程原则上,异常只应表示错误状态,切忌当成普通条件跳转指令滥用。
一旦 `throw` 抛出异常,其后同块代码不再执行,PHP 会沿调用栈向上寻找匹配的 `catch` 块。如果既未被任何 `catch` 捕获又未注册 `set_exception_handler()`,脚本将因 `Fatal error: Uncaught Exception` 立即中止并打印堆栈追踪(例如 `checkNum(2)` 直接抛出未捕获异常)。
Try、Throw、Catch 与 Finally 协作
规范的异常处理包含 `try`(包裹可能抛出异常的调用)、`throw`(显式抛出异常对象)与 `catch`(按类型捕获异常对象并读取信息),现代 PHP 还可附加必然执行的 `finally` 块用于资源清理。若 `try` 内触发异常,后续语句跳过并转入 `catch(Exception $e)`,调用 `$e->getMessage()` 即可输出 `Message: 变量值必须小于等于 1`。
对照 `checkNum()` 实例的执行轨迹:函数检测 `$number > 1` 时抛出 `Exception`,`try` 块中调用 `checkNum(2)` 触发抛出,随后 `catch` 接收 `$e` 并输出其消息。本站 PHP 8.4.27 实测对比双分支:`checkNum(1)` 返回 `true` 且执行 `try` 后续语句与 `finally`;`checkNum(2)` 跳过后续语句进入 `catch` 输出 `Message: 变量值必须小于等于 1`,且 `finally` 仍为 `true`。为避免漏捕,还可在入口注册顶层异常处理器兜底。
自定义 Exception 子类与多异常捕获
继承内置 `Exception` 类即可创建业务专用异常类(如 `CustomEmailException`),它天然拥有 `getLine()`、`getFile()`、`getMessage()` 等方法,并可扩展自定义的 `errorMessage()` 格式化逻辑。当 `filter_var($email, FILTER_VALIDATE_EMAIL) === false` 判定 `someone@example...com` 非法时抛出该子类,`catch (CustomEmailException $e)` 捕获后输出含行号、脚本名与邮箱信息的定制错误。本站 PHP 8.4.27 实测确认捕获成功、行号为正整数且消息包含 `explore-exception.php` 与 `someone@example...com 不是一个合法的 E-Mail 地址`。
同一段 `try` 逻辑可针对不同条件抛出不同异常类,再按“先子类后父类”的顺序配置多个 `catch` 块。以 `someone@example.com` 为例:它通过了邮箱格式检查(不抛 `CustomEmailException`),却命中了包含 `example` 字样的第二条规则而抛出基类 `Exception`,最终由第二个 `catch (Exception $e)` 捕获。注意如果只写基类 `catch (Exception $e)` 而未单独捕获子类,子类异常也会被基类分支兜底接住。
重新抛出异常、顶层处理器与核心规则
面对底层系统异常时,常希望隐藏内部实现细节并向用户返回更友好的业务提示,此时可在内层 `catch` 中重新抛出(rethrow)一个新的自定义异常对象,由外层 `try/catch` 统一捕获并展示(建议传入原异常作为 `$previous` 参数保留完整根因链)。本站 PHP 8.4.27 实测内层捕获 `Exception` 后重抛 `CustomEmailException`,外层输出 `someone@example.com 不是一个合法的 E-Mail 地址。` 且 `$e->getPrevious() instanceof Exception` 为 `true`。
`set_exception_handler()` 可注册全局顶层回调函数接管所有未被 `catch` 捕获的异常(PHP 7+ 建议参数类型为 `Throwable` 以同时兼容 `Error`),脚本执行顶层回调后将正常结束退出。本站实测确认 `set_exception_handler()` 首次返回 `null`、重置时返回已注册回调引用,且回调格式化 `Uncaught Exception occurred` 为 `Exception: Uncaught Exception occurred`。综上须遵循四条基本准则:高风险代码放入 `try`;每个 `try` 至少配一个 `catch`(或 `finally`);多 `catch` 区分异常层级;支持在 `catch` 内重抛——核心原则是有抛必有捕。
运行 PHP 8.4 try/catch/finally、自定义异常、重抛与顶层处理器实验
展开查看收起
<?php
declare(strict_types=1);
class CustomEmailException extends Exception
{
public function errorMessage(): string
{
return '错误行号 ' . $this->getLine() . ' in ' . basename($this->getFile())
. ': ' . $this->getMessage() . ' 不是一个合法的 E-Mail 地址';
}
}
function checkNum(int $number): bool
{
if ($number > 1) {
throw new Exception('变量值必须小于等于 1');
}
return true;
}
$cases = [];
// Case 1: Basic try / throw / catch / finally control flow
$okReachedAfter = false;
$okFinally = false;
try {
$okResult = checkNum(1);
$okReachedAfter = true;
} finally {
$okFinally = true;
}
$errReachedAfter = false;
$errMessage = '';
$errFinally = false;
try {
checkNum(2);
$errReachedAfter = true;
} catch (Exception $e) {
$errMessage = 'Message: ' . $e->getMessage();
} finally {
$errFinally = true;
}
$actual1 = [
'ok_result' => $okResult,
'ok_reached_after' => $okReachedAfter,
'ok_finally' => $okFinally,
'err_reached_after' => $errReachedAfter,
'err_message' => $errMessage,
'err_finally' => $errFinally,
];
$expected1 = [
'ok_result' => true,
'ok_reached_after' => true,
'ok_finally' => true,
'err_reached_after' => false,
'err_message' => 'Message: 变量值必须小于等于 1',
'err_finally' => true,
];
$cases[] = [
'name' => 'try_throw_catch_finally',
'passed' => $actual1 === $expected1,
'expected' => $expected1,
'actual' => $actual1,
];
// Case 2: Custom Exception subclass inheriting getLine()/getFile()/getMessage()
$badEmail = 'someone@example...com';
$customMsg = '';
$customLine = 0;
try {
if (filter_var($badEmail, FILTER_VALIDATE_EMAIL) === false) {
throw new CustomEmailException($badEmail);
}
} catch (CustomEmailException $e) {
$customMsg = $e->errorMessage();
$customLine = $e->getLine();
}
$actual2 = [
'caught_custom' => $customMsg !== '',
'line_positive' => $customLine > 0,
'contains_file' => str_contains($customMsg, 'explore-exception.php'),
'contains_email' => str_contains($customMsg, 'someone@example...com 不是一个合法的 E-Mail 地址'),
];
$expected2 = [
'caught_custom' => true,
'line_positive' => true,
'contains_file' => true,
'contains_email' => true,
];
$cases[] = [
'name' => 'custom_exception_subclass',
'passed' => $actual2 === $expected2,
'expected' => $expected2,
'actual' => $actual2,
];
// Case 3: Multiple catch blocks & rethrowing Exception as user-friendly CustomEmailException
$email = 'someone@example.com';
$multiCatchBranch = '';
try {
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
throw new CustomEmailException($email);
}
if (str_contains($email, 'example')) {
throw new Exception("$email 是 example 邮箱");
}
} catch (CustomEmailException $e) {
$multiCatchBranch = 'custom:' . $e->errorMessage();
} catch (Exception $e) {
$multiCatchBranch = 'base:' . $e->getMessage();
}
$rethrowResult = '';
try {
try {
if (str_contains($email, 'example')) {
throw new Exception($email);
}
} catch (Exception $e) {
throw new CustomEmailException($e->getMessage(), 0, $e);
}
} catch (CustomEmailException $e) {
$rethrowResult = $e->getMessage() . ' 不是一个合法的 E-Mail 地址。';
$hasPrevious = $e->getPrevious() instanceof Exception;
}
$actual3 = [
'multi_catch_branch' => $multiCatchBranch,
'rethrow_result' => $rethrowResult,
'preserves_previous' => $hasPrevious,
];
$expected3 = [
'multi_catch_branch' => 'base:someone@example.com 是 example 邮箱',
'rethrow_result' => 'someone@example.com 不是一个合法的 E-Mail 地址。',
'preserves_previous' => true,
];
$cases[] = [
'name' => 'multiple_catch_and_rethrow',
'passed' => $actual3 === $expected3,
'expected' => $expected3,
'actual' => $actual3,
];
// Case 4: set_exception_handler() registration and handler formatting
$handler = static function (Throwable $exception): string {
return 'Exception: ' . $exception->getMessage();
};
$prevBefore = set_exception_handler($handler);
$prevOnReset = set_exception_handler(null);
restore_exception_handler();
restore_exception_handler();
$formatted = $handler(new Exception('Uncaught Exception occurred'));
$actual4 = [
'prev_initially_null' => $prevBefore === null,
'registered_callable_returned' => $prevOnReset === $handler,
'handler_output' => $formatted,
];
$expected4 = [
'prev_initially_null' => true,
'registered_callable_returned' => true,
'handler_output' => 'Exception: Uncaught Exception occurred',
];
$cases[] = [
'name' => 'top_level_exception_handler_registration',
'passed' => $actual4 === $expected4,
'expected' => $expected4,
'actual' => $actual4,
];
echo json_encode(['version' => PHP_VERSION, 'cases' => $cases], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n";
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
PHP 按自上而下顺序匹配第一个兼容类型,若把基类 `Exception` 放在前面,子类异常也会被基类分支截获,导致子类分支永远无法执行;重抛时将原异常传给构造器第三个参数 `$previous`,可在对外展示友好提示的同时于日志中保留原始根因堆栈。