博客
关于我
php异常处理
阅读量:793 次
发布时间:2023-03-01

本文共 1784 字,大约阅读时间需要 5 分钟。

异常处理的基石:try-catch-block

try、catch、throw是PHP中用于处理异常的三大关键字。它们是程序开发中最基础的错误处理机制。通过try-catch结构,可以捕获程序运行过程中出现的异常,采取相应措施进行修复或记录。

1) {
throw new Exception("Value must be 1 or below");
}
return true;
}
try {
checkNum(2);
echo 'If you see this, the number is 1 or below';
} catch(Exception $e) {
echo 'Message: ' . $e->getMessage();
}

自定义异常处理:创建专用异常类

除了PHP内置的Exception类,开发者还可以创建自定义异常类。自定义异常类可以包含更多的错误信息,方便 debugging和日志记录。

getLine() . ' in ' . $this->getFile()
. ': ' . $this->getMessage() . ' is not a valid E-Mail address';
return $errorMsg;
}
}
$email = "someone@example.com";
try {
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
throw new customException($email);
}
} catch (customException $e) {
echo $e->errorMessage();
}

多个异常捕获:优先处理特定错误

在try-catch结构中,catch语句可以捕获多个异常类型,但需要注意的是,后面的catch必须放在前面的catch之后。这样可以确保优先处理特定异常类型。

getLine() . ' in ' . $this->getFile()
. ': ' . $this->getMessage() . ' is not a valid E-Mail address';
return $errorMsg;
}
}
$email = "someone@example.com";
try {
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
throw new customException($email);
}
if(strpos($email, "example") !== FALSE) {
throw new Exception("$email is an example e-mail");
}
} catch (customException $e) {
echo $e->errorMessage();
} catch (Exception $e) {
echo $e->getMessage();
}

全局异常处理:set_exception_handler

set_exception_handler函数可以注册一个全局的异常处理函数。无论程序中抛出的异常是否被捕获,都会调用这个函数进行处理。

getMessage();
}
set_exception_handler('myException');
// 以下代码会抛出异常
throw new Exception('Uncaught Exception occurred');
// 后面的代码不会执行
// 输出:Exception: Uncaught Exception occurred

触发错误:强制抛出错误

trigger_error函数可以在代码中强制触发错误或异常。这通常用于测试错误处理逻辑或在特定条件下触发预期的错误。

转载地址:http://pptfk.baihongyu.com/

你可能感兴趣的文章
PHP-DI/Invoker 开源项目使用教程
查看>>
php-fpm与Nginx运行常见错误说明
查看>>
php-fpm比php成为apache模块好在哪
查看>>
php-fpm超时时间设置request_terminate_timeout分析
查看>>
PHP-GD库-分类整理
查看>>
php-laravel框架用户验证(Auth)模块解析(一)
查看>>
php-laravel框架用户验证(Auth)模块解析(三)登录模块
查看>>
php-laravel框架用户验证(Auth)模块解析(二)注册模块
查看>>
php-laravel框架用户验证(Auth)模块解析(四)忘记密码
查看>>
php-redis中文参考手册_Ping_echo_set_get_setex_psetex_...
查看>>
PHP-Shopify-API-Wrapper 使用教程
查看>>
php-兔子问题,斐波那契数列
查看>>
PHP-希尔排序
查看>>
PHP-快速排序的2种实现方法
查看>>
php-数据结构-二叉树的构建、前序遍历,中序遍历,后序遍历,查找,打印
查看>>
php-有序数组合并后仍有序
查看>>
redis使用
查看>>
Redis以及Redis的php扩展安装
查看>>
PHP-算法-最少比较次数获取最大值最小值
查看>>
php-约瑟夫问题
查看>>