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

本文共 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函数可以在代码中强制触发错误或异常。这通常用于测试错误处理逻辑或在特定条件下触发预期的错误。

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

你可能感兴趣的文章
PHP学习总结(4)——PHP入门篇之PHP计算表达式
查看>>
PHP学习总结(5)——PHP入门篇之PHP字符串
查看>>
PHP学习总结(6)——PHP入门篇之PHP语句结束符
查看>>
PHP学习总结(7)——PHP入门篇之PHP注释
查看>>
rabbitmq重启失败
查看>>
PHP学习总结(9)——PHP入门篇之WAMPServer服务控制面板介绍
查看>>
php学习笔记---php调试和开发工具整理
查看>>
PHP学习笔记一:谁动了你的mail(),PHP?
查看>>
PHP安全实战
查看>>
php安装扩展
查看>>
php实战第二十二天
查看>>
rabbitmq重启
查看>>
php实现上传(多个)文件函数封装
查看>>
php实现下载文件方法
查看>>
php实现单链表
查看>>
php实现图片背景换色功能
查看>>
php实现多个一维数组对应合并成二维数组
查看>>
php实现多关键字查找方法
查看>>
PHP实现微信公众号H5支付
查看>>
PHP实现微信公众号网页授权
查看>>