php异常实现
PHP 异常处理基础
PHP 异常处理通过 try、catch、throw 和 finally 关键字实现。异常用于在程序执行过程中遇到错误时改变正常流程。
try {
// 可能抛出异常的代码
if ($errorCondition) {
throw new Exception("Error message");
}
} catch (Exception $e) {
// 处理异常
echo "Caught exception: " . $e->getMessage();
} finally {
// 无论是否抛出异常都会执行的代码
echo "This always runs";
}
自定义异常类
可以继承 Exception 类创建特定于应用的异常类型,添加额外功能或特定错误信息。

class CustomException extends Exception {
public function errorMessage() {
return "Custom error on line {$this->getLine()} in {$this->getFile()}";
}
}
try {
throw new CustomException("Custom error");
} catch (CustomException $e) {
echo $e->errorMessage();
}
多异常捕获
PHP 7.1+ 支持在单个 catch 块中捕获多种异常类型,简化代码结构。

try {
// 可能抛出多种异常的代码
} catch (CustomException | OtherException $e) {
// 处理两种异常
echo $e->getMessage();
}
异常传播
未被捕获的异常会沿调用栈向上传播,直到被捕获或导致致命错误。可以设置全局异常处理器处理未被捕获的异常。
set_exception_handler(function($exception) {
echo "Uncaught exception: " . $exception->getMessage();
});
// 这个异常如果没有被捕获,会触发全局处理器
throw new Exception("Uncaught");
PDO 异常处理
使用 PDO 进行数据库操作时,可以设置错误模式为异常模式,使数据库错误抛出异常而非返回错误代码。
$pdo = new PDO($dsn, $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$stmt = $pdo->query("INVALID SQL");
} catch (PDOException $e) {
echo "Database error: " . $e->getMessage();
}
最佳实践
- 为特定错误条件创建专门的异常类
- 在适当层级捕获异常,不要过早捕获无法处理的异常
- 记录异常详细信息以便调试
- 清理资源使用
finally块 - 避免空的
catch块,至少要记录异常
try {
$resource = acquireResource();
// 使用资源
} catch (ResourceException $e) {
logError($e->getMessage());
throw $e; // 重新抛出给上层处理
} finally {
if (isset($resource)) {
releaseResource($resource);
}
}






