php中的异常和错误处理机制包括异常(可恢复)和错误(不可恢复)。异常使用try-catch处理,错误使用error_get_last()获取信息和set_error_handler()自定义处理函数。异常通过throw语句抛出,使用try-catch捕获,异常对象提供错误信息、代码、文件和行号。

在 PHP 中,异常和错误是两种不同的错误处理机制:
try-catch 语句来处理。PHP 内置了一个错误处理函数 error_get_last(),用于获取最近发生的错误信息:
<?php
// 触发一个错误
echo $undefined_variable;
// 获取错误信息
$error = error_get_last();
if ($error) {
echo "错误类型:{$error['type']}" . PHP_EOL;
echo "错误信息:{$error['message']}" . PHP_EOL;
echo "错误文件:{$error['file']}" . PHP_EOL;
echo "错误行号:{$error['line']}" . PHP_EOL;
}还可以使用 set_error_handler() 函数自定义错误处理函数:
立即学习“PHP免费学习笔记(深入)”;
<?php
function my_error_handler($errno, $errstr, $errfile, $errline) {
echo "错误类型:{$errno}" . PHP_EOL;
echo "错误信息:{$errstr}" . PHP_EOL;
echo "错误文件:{$errfile}" . PHP_EOL;
echo "错误行号:{$errline}" . PHP_EOL;
}
set_error_handler('my_error_handler');
// 触发一个错误
echo $undefined_variable;抛出异常
可以使用 throw 语句抛出异常:
<?php
function divide($num1, $num2) {
if ($num2 === 0) {
throw new Exception("除数不能为 0");
}
return $num1 / $num2;
}捕获异常
可以使用 try-catch 语句捕获异常:
<?php
try {
divide(10, 0);
} catch (Exception $e) {
echo "异常信息:{$e->getMessage()}" . PHP_EOL;
}异常对象提供了以下信息:
getMessage():异常消息getCode():异常代码getFile():异常发生的文件getLine():异常发生的行号实战案例
以下是一个检查文件是否存在并抛出异常的 PHP 函数:
<?php
function file_exists_or_throw($path) {
if (!file_exists($path)) {
throw new Exception("文件 '{$path}' 不存在");
}
}这个函数可以在需要确保文件存在的情况下使用:
<?php
try {
file_exists_or_throw('test.txt');
// ...
} catch (Exception $e) {
echo "文件 'test.txt' 不存在" . PHP_EOL;
}以上就是PHP 函数中异常和错误处理的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号