在PHP中,异常处理是管理运行时错误和自定义错误条件的关键机制。通过合理的异常处理,可以提升代码的健壮性、可读性和可维护性。以下是PHP异常处理的详细指南:

一、基础异常处理

1.块

try-catch

php

try { // 可能抛出异常的代码 $file = fopen("", "r"); if (!$file) { throw new Exception("无法打开文件"); } // 其他操作...} catch (Exception $e) { // 捕获异常并处理 echo "错误: " . $e->getMessage();} finally { // 无论是否异常都会执行的代码(可选) echo "操作完成";}

2. 自定义异常类

php

class DatabaseException extends Exception { public function __construct($message, $code = 0) { parent::__construct($message, $code); }}try { $db = new PDO("mysql:host=localhost;dbname=test", "user", "password"); if (!$db) { throw new DatabaseException("数据库连接失败"); }} catch (DatabaseException $e) { echo "数据库错误: " . $e->getMessage();}

二、异常处理进阶

1. 多异常捕获

php

try { // 代码可能抛出多种异常} catch (InvalidArgumentException $e) { echo "参数错误: " . $e->getMessage();} catch (RuntimeException $e) { echo "运行时错误: " . $e->getMessage();} catch (Exception $e) { echo "通用错误: " . $e->getMessage();}

2. 重新抛出异常

php

try { try { // 嵌套操作 } catch (Exception $e) { // 记录日志后重新抛出 error_log($e->getMessage()); throw $e; }} catch (Exception $e) { echo "外层捕获: " . $e->getMessage();}

三、全局异常处理

1. 设置全局异常处理器

php

set_exception_handler(function (Throwable $e) { // 记录日志或显示友好错误页面 error_log("未捕获异常: " . $e->getMessage()); include "error_page.php";});// 触发未捕获异常throw new Exception("测试全局异常");

2. 结合错误报告

php

// 开启所有错误报告error_reporting(E_ALL);ini_set('display_errors', 0); // 生产环境关闭错误显示// 将错误转换为异常set_error_handler(function ($severity, $message, $file, $line) { throw new ErrorException($message, 0, $severity, $file, $line