php5和php7的异常处理机制(thinkphp5 异常处理的分析)
本篇文章主要给大家介绍php5和php7的异常处理机制(thinkphp5 异常处理的分析),希望对需要的朋友有所帮助!
1.php异常和错误
在其他语言中,异常和错误是有区别的,但是PHP,遇见自身错误时,会触发一个错误,而不是跑出异常。并且,php大部分情况,都会触发错误,终止程序执行,在php5中,try catch是没有办法处理错误的。
php7是可以捕获错误的;
1.1 php5 错误异常
// 1.异常处理 try{ throw new Exception("Error Processing Request", 1); }catch ( Exception $e){ echo $e->getCode().'<br/>'; echo $e->getMessage().'<br/>'; echo $e->getLine().'<br/>'; echo $e->getFile().'<br/>'; } 返回: 1 Error Processing Request 158 E:\phpwebenv\PHPTutorial\WWW\test\index.php // 2.结果php错误处理机制 function MyErrorHandler($error,$errstr,$errfile,$errline){ echo '<b> Custom error:</b>'.$error.':'.$errstr.'<br/>'; echo "Error on line $errline in ".$errfile; } set_error_handler('MyErrorHandler',E_ALL|E_STRICT); try{ // throw new Exception("Error Processing Request", 4); trigger_error('error_msg'); }catch ( Exception $e){ echo $e->getCode().'<br/>'; echo $e->getMessage().'<br/>'; echo $e->getLine().'<br/>'; echo $e->getFile().'<br/>'; } 结果: Custom error:1024:error_msg Error on line 164 in E:\phpwebenv\PHPTutorial\WWW\test\index.php //3. 处理致命错误:脚本结束后执行 function shutdown_function(){ $e = error_get_last(); echo '<pre/>'; var_dump($e); } register_shutdown_function('shutdown_function'); try{ // throw new Exception("Error Processing Request", 4); // trigger_error('error_msg'); fun(); }catch ( Exception $e){ echo $e->getCode().'<br/>'; echo $e->getMessage().'<br/>'; echo $e->getLine().'<br/>'; echo $e->getFile().'<br/>'; } 结果: Fatal error: Uncaught Error: Call to undefined function fun() in E:\phpwebenv\PHPTutorial\WWW\ test\index.php:172 Stack trace: #0 {main} thrown in E:\phpwebenv\PHPTutorial\WWW\test\index.php on line 172 array(4) { ["type"]=> int(1) ["message"]=> string(131) "Uncaught Error: Call to undefined function fun() in E:\phpwebenv\PHPTutorial\WWW\test\index.php:172 Stack trace: #0 {main} thrown" ["file"]=> string(43) "E:\phpwebenv\PHPTutorial\WWW\test\index.php" ["line"]=> int(172) } 以上方法可以看出,php没有捕获到异常,只能依赖set_error_handler()和register_shutdown_function();来处理,set_error_handler只能接受 异常和非致命的错误。register_shutdown_function():主要针对die()或致命错误,即程序终结后执行;所以php5没有很好的异常处理机制。
1.2 php7的异常处理
// 处理致命错误:脚本结束后执行 function shutdown_function(){ $e = error_get_last(); echo '<pre class="brush:php;toolbar:false">'; var_dump($e); } register_shutdown_function('shutdown_function'); // 结果php错误处理机制 function MyErrorHandler($error,$errstr,$errfile,$errline){ echo '<b> Custom error:</b>'.$error.':'.$errstr.'<br/>'; echo "Error on line $errline in ".$errfile; } set_error_handler('MyErrorHandler',E_ALL|E_STRICT); try{ // throw new Exception("Error Processing Request", 4); // trigger_error('error_msg'); fun(); }catch ( Error $e){ echo $e->getCode().'<br/>'; echo $e->getMessage().'<br/>'; echo $e->getLine().'<br/>'; echo $e->getFile().'<br/>'; } 结果: 0 Call to undefined function fun() 172 E:\phpwebenv\PHPTutorial\WWW\test\index.php NULL register_shutdown_function();没有捕获到异常
// 2. 如果不用try catch 捕获 function exception_handler( Throwable $e){ echo 'catch Error:'.$e->getCode().':'.$e->getMessage().'<br/>'; } set_exception_handler('exception_handler'); fun();
总结: Throwable 是Error 和 Exception 的基类,在php7中,如果既想捕获异常有需要捕获错误
try{ fun(); }catch ( Throwable $e){ echo $e->getCode().'<br/>'; echo $e->getMessage().'<br/>'; echo $e->getLine().'<br/>'; echo $e->getFile().'<br/>'; }
3. thinkphp5框架的错误处理:
在异常错误处理类:Error有这个处理 // 注册错误和异常处理机制 \think\Error::register(); /** * 注册异常处理 * @return void */ public static function register() { error_reporting(E_ALL); set_error_handler([__CLASS__, 'appError']); set_exception_handler([__CLASS__, 'appException']); register_shutdown_function([__CLASS__, 'appShutdown']); } 当程序出现错误时,会执行这些异常、错误的函数;
链接数据库后,处理异常的是:
/** * 连接数据库方法 * @access public * @param array $config 连接参数 * @param integer $linkNum 连接序号 * @param array|bool $autoConnection 是否自动连接主数据库(用于分布式) * @return PDO * @throws Exception */ public function connect(array $config = [], $linkNum = 0, $autoConnection = false) { if (!isset($this->links[$linkNum])) { if (!$config) { $config = $this->config; } else { $config = array_merge($this->config, $config); } // 连接参数 if (isset($config['params']) && is_array($config['params'])) { $params = $config['params'] + $this->params; } else { $params = $this->params; } // 记录当前字段属性大小写设置 $this->attrCase = $params[PDO::ATTR_CASE]; // 数据返回类型 if (isset($config['result_type'])) { $this->fetchType = $config['result_type']; } try { if (empty($config['dsn'])) { $config['dsn'] = $this->parseDsn($config); } if ($config['debug']) { $startTime = microtime(true); } $this->links[$linkNum] = new PDO($config['dsn'], $config['username'], $config['password'], $params); if ($config['debug']) { // 记录数据库连接信息 Log::record('[ DB ] CONNECT:[ UseTime:' . number_format(microtime(true) - $startTime, 6) . 's ] ' . $config['dsn'], 'sql'); } } catch (\PDOException $e) { if ($autoConnection) { Log::record($e->getMessage(), 'error'); return $this->connect($autoConnection, $linkNum); } else { throw $e; } } } return $this->links[$linkNum]; } 当数据库链接失败后,可以重新链接或者直接抛出异常; /** * 析构方法 * @access public */ public function __destruct() { // 释放查询 if ($this->PDOStatement) { $this->free(); } // 关闭连接 $this->close(); } 当执行sql失败后,调用析构方法,关闭数据库链接;
4. php发生错误时,资源释放
php是解释性脚本,每个php页面都是一个独立的执行程序,不管用什么方式只要执行完了(包括die(),exit(),致命错误终止程序),都会把结果返回给服务器,都会关闭。程序都关闭了,资源当然会被释放;
unset();当多个变量名或者对象名指向一块存储地址时,unset()函数的作用仅仅是销毁变量名和存储地址的指向而已,当仅有一个变量名或者对象名,unset销毁的是指定的存储地址上的内容;
析构方法:当实例化的对象,没有其他变量或对象名指向时,就会执行此方法;或者是在脚本结束后,释放对象资源时,执行此方法;
相关推荐:
以上是php5和php7的异常处理机制(thinkphp5 异常处理的分析)的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undress AI Tool
免费脱衣服图片

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

php5和php8的区别在性能、语言结构、类型系统、错误处理、异步编程、标准库函数和安全性等方面。详细介绍:1、性能提升,PHP8相对于PHP5来说在性能方面有了巨大的提升,PHP8引入了JIT编译器,可以对一些高频执行的代码进行编译和优化,从而提高运行速度;2、语言结构改进,PHP8引入了一些新的语言结构和功能,PHP8支持命名参数,允许开发者通过参数名而不是参数顺序等等。

解决 PHP 7.0 中插件未显示已安装问题的方法:检查插件配置并启用插件。重新启动 PHP 以应用配置更改。检查插件文件权限,确保其正确。安装丢失的依赖项,以确保插件正常运行。如果其他步骤均失败,则重建 PHP。其他可能原因包括插件版本不兼容、加载错误版本或 PHP 配置问题。

在php5中,我们可以使用fsockopen()函数来检测TCP端口。这个函数可以用来打开一个网络连接和进行一些网络通信。但是在php7中,fsockopen()函数可能会遇到一些问题,例如无法打开端口、无法连接到服务器等。为了解决这个问题,我们可以使用socket_create()函数和socket_connect()函数来检测TCP端口。

php7.0安装mongo扩展的方法:1、创建mongodb用户组和用户;2、下载mongodb源码包,并将源码包放到“/usr/local/src/”目录下;3、进入“src/”目录;4、解压源码包;5、创建mongodb文件目录;6、将文件复制到“mongodb/”目录;7、创建mongodb配置文件并修改配置即可。

PHP服务器环境常见的解决方法包括:确保已安装正确的PHP版本和已复制相关文件到模块目录。临时或永久禁用SELinux。检查并配置PHP.ini,确保已添加必要的扩展和进行正确设置。启动或重启PHP-FPM服务。检查DNS设置是否存在解析问题。

在Docker环境中使用PECL安装扩展时报错的原因及解决方法在使用Docker环境时,我们常常会遇到一些令人头疼的问�...

php5改80端口的方法:1、编辑Apache服务器的配置文件中的端口号;2、辑PHP的配置文件以确保PHP在新端口上工作;3、重启Apache服务器,PHP应用程序将开始在新的端口上运行。

如何在系统重启后自动设置unixsocket的权限每次系统重启后,我们都需要执行以下命令来修改unixsocket的权限:sudo...
