php异常处理
发布日期:2025-05-04 10:24:23
浏览次数:10
分类:精选文章
本文共 1739 字,大约阅读时间需要 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函数可以在代码中强制触发错误或异常。这通常用于测试错误处理逻辑或在特定条件下触发预期的错误。
发表评论
最新留言
感谢大佬
[***.8.128.20]2026年06月15日 16时08分42秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
php把get参数放入数组_php怎么将数组转为url参数?
2023-03-01
PHP投票小程序
2023-03-01
php拆分数组不改变key值
2023-03-01
php接口返回数据 用echo 还是return?
2023-03-01
php接口返回状态,大家一般怎么规范接口返回内容
2023-03-01
php接收formdata上传的多个文件,使用formData()上传多个文件
2023-03-01
PHP操作csv文件导入+导出
2023-03-01
php操作mysql用select_php如何操作mysql获取select 结果
2023-03-01
PHP操作符与控制结构
2023-03-01
PHP支付宝SDK使用,电脑网页支付
2023-03-01
php支付宝手机网页支付类实例
2023-03-01
PHP改变数组key值的方法
2023-03-01
php教程之php空白页的原因及解决方法
2023-03-01
PHP数据库操作
2023-03-01
PHP数据文件过大,导致PHP加速器eaccelerator在PHP5.2版本下崩溃
2023-03-01
RabbitMQ - 死信、TTL原理、延迟队列安装和配置
2023-03-01
PHP数据访问的多重查询(租房子查询)
2023-03-01
RabbitMQ - 如保证消息的可靠性?(消息确认、消息持久化、失败重试机制)
2023-03-01
RabbitMQ - 基于 SpringAMQP 带你实现五种消息队列模型
2023-03-01
php数组函数分析--array_column
2023-03-01