PHP异常抛出时机与性能影响
2026/6/9 9:19:46 网站建设 项目流程

PHP异常抛出时机与性能影响

异常处理的性能开销比正常流程大。合理使用异常可以提高代码质量,滥用则会影响性能。今天说说PHP异常抛出的时机和性能影响。

异常的性能开销。

```php
function benchmarkException(): void
{
$start = microtime(true);
for ($i = 0; $i < 10000; $i++) {
if (rand(0, 1) === 0) {
// 正常流程
$result = 1 + 1;
} else {
// 异常流程
try {
throw new RuntimeException("测试");
} catch (RuntimeException $e) {
$result = 0;
}
}
}
echo "异常路径: " . round((microtime(true) - $start) * 1000, 2) . "ms\n";

$start = microtime(true);
for ($i = 0; $i < 10000; $i++) {
// 不用异常
$result = rand(0, 1) === 0 ? 1 + 1 : 0;
}
echo "正常路径: " . round((microtime(true) - $start) * 1000, 2) . "ms\n";
}

benchmarkException();
?>

异常的正确用途。

```php
// 错误:用异常做流程控制
function divideBad(int $a, int $b): float
{
if ($b === 0) {
throw new InvalidArgumentException("不能为0");
}
return $a / $b;
}

// 正确:异常用于确实异常的情况
class UserService
{
public function findUser(int $id): User
{
$user = $this->repository->find($id);
if ($user === null) {
throw new UserNotFoundException("用户不存在");
}
return $user;
}
}
?>

异常和错误码的选择。

```php
// 可预见的错误用返回值
function parseConfig(string $path): ?array
{
if (!file_exists($path)) return null;
$config = parse_ini_file($path, true);
return $config !== false ? $config : null;
}

// 不可预见的错误用异常
function processPayment(float $amount): void
{
if ($amount <= 0) {
throw new InvalidArgumentException("金额无效");
}

try {
$gateway = new PaymentGateway();
$gateway->charge($amount);
} catch (GatewayException $e) {
throw new PaymentException("支付失败", 0, $e);
}
}
?>

异常处理的最佳实践。

```php
// 1. 只在真正异常的情况下抛出异常
// 2. 用不同的异常类型区分不同的错误
// 3. 在合适的层级捕获异常
// 4. 不要用异常做流程控制
// 5. 记录异常的上下文信息

function processOrder(array $order): void
{
try {
validateOrder($order);
$payment = processPayment($order['amount']);
saveOrder($order, $payment);
sendNotification($order);
} catch (ValidationException $e) {
// 业务错误,可以恢复
throw $e;
} catch (PaymentException $e) {
// 支付失败,记录日志
error_log("支付失败: {$e->getMessage()}");
throw $e;
} catch (Throwable $e) {
// 系统错误,记录详细日志
error_log("系统错误: {$e->getMessage()} in {$e->getFile()}:{$e->getLine()}");
throw new RuntimeException("系统错误", 0, $e);
}
}
?>

异常的传播。

```php
function a(): void { b(); }
function b(): void { c(); }
function c(): void { throw new RuntimeException("最深处的错误"); }

try {
a();
} catch (RuntimeException $e) {
echo "捕获: {$e->getMessage()}\n";
}
?>

异常是处理错误的好工具,但不要滥用。异常的性能开销比正常路径大,只在确实异常的情况下使用。可预见的错误用返回值处理。理解异常机制可以在代码质量和性能之间取得平衡。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询