Skip to content

错误处理与异常处理

错误类型

Notice:

非致命性运行错误,通常是轻微的问题,不会导致脚本停止执行。例如访问未定义的变量。

php
echo $undefined_variable; // 产生 Notice 错误

Warning:

运行时警告,不会中止脚本的执行,但会显示问题的原因。例如尝试包含一个不存在的文件。

php
include("non_existent_file.php"); // 产生 Warning 错误

Error:

致命性错误,会导致脚本停止执行。例如调用不存在的函数。

php
undefined_function(); // 产生致命性错误

错误处理函数

set_error_handler()

自定义错误处理函数,替换 PHP 默认的错误处理机制。

php
function customErrorHandler($errno, $errstr, $errfile, $errline) {
    echo "Error [$errno]: $errstr in $errfile on line $errline<br>";
}

// 设置自定义错误处理函数
set_error_handler("customErrorHandler");

// 触发一个用户级别的 Notice 错误
trigger_error("This is a custom notice.", E_USER_NOTICE);

error_reporting()

设置 PHP 报告的错误级别。

php
// 禁用所有错误报告
error_reporting(0);

// 报告所有错误
error_reporting(E_ALL);

// 只报告警告和致命性错误
error_reporting(E_WARNING | E_ERROR);

日志记录:

可以通过配置 php.ini 中的 log_errorserror_log 指令,将错误记录到日志文件中。

ini
log_errors = On
error_log = /path/to/error.log

异常处理

try-catch 机制:

使用 try-catch 捕获异常,防止脚本在发生错误时直接中止执行。

php
try {
    if (!file_exists("example.txt")) {
        throw new Exception("File not found.");
    }
} catch (Exception $e) {
    echo "Caught exception: " . $e->getMessage();
}

finally 语句:

无论是否发生异常,finally 中的代码总会执行,通常用于清理操作。

php
try {
    // 可能抛出异常的代码
    throw new Exception("An error occurred.");
} catch (Exception $e) {
    echo "Caught exception: " . $e->getMessage();
} finally {
    echo "This code runs regardless of whether an exception occurred.";
}

多异常处理:

可以在同一个 try 语句中捕获多种类型的异常。

php
try {
    // 可能抛出不同类型的异常
} catch (InvalidArgumentException $e) {
    echo "Invalid argument: " . $e->getMessage();
} catch (Exception $e) {
    echo "General exception: " . $e->getMessage();
}

自定义异常

定义自定义异常类:

继承 Exception 类来创建自定义异常。

php
class CustomException extends Exception {
    public function errorMessage() {
        return "Custom error on line " . $this->getLine() . " in " . $this->getFile() . ": " . $this->getMessage();
    }
}

try {
    throw new CustomException("This is a custom exception.");
} catch (CustomException $e) {
    echo $e->errorMessage();
}

自定义异常处理:

可以通过 set_exception_handler() 自定义异常处理函数。

php
function customExceptionHandler($exception) {
    echo "Custom exception: " . $exception->getMessage();
}

// 设置自定义异常处理函数
set_exception_handler("customExceptionHandler");

// 触发异常
throw new Exception("An unexpected error occurred.");

错误与异常的区别

  • 错误:通常是代码中的语法或运行时问题,例如未定义的函数或变量,无法通过捕获异常来处理。
  • 异常:在程序运行期间由程序员使用 throw 关键字显式触发,适用于处理特定的错误场景。
编程洪同学服务平台是一个广泛收集编程相关内容和资源,旨在满足编程爱好者和专业开发人员的需求的网站。无论您是初学者还是经验丰富的开发者,都可以在这里找到有用的信息和资料,我们将助您提升编程技能和知识。
专业开发
高端定制
售后无忧
站内资源均为本站制作或收集于互联网等平台,如有侵权,请第一时间联系本站,敬请谅解!本站资源仅限于学习与参考,严禁用于各种非法活动,否则后果自行负责,本站概不承担!